Allow Register
-ing of the QueryKey
type via module augmentation
#8495
-
I'm working on a codebase that has a fairly straightforward hierarchy, and where generally we have the first part of a queryKey: ["paymentsDashboard", "payment", payment.id]
queryKey: ["accountDashboard", "usersList", currentCursor]
queryKey: ["global", "currentUser", user.id] We use these "areas" to easily invalidate the relevant part of the app depending on what type of mutation has happened. As an example, we will always invalidate To get around this, we can create an enum or other typed utility in user-land, to help us create Exposing this ability would help solve this problem at a lower level than is possible in user-land, and with the added benefit of allowing enforcement. This TS Playground gives an example of how we could benefit from updating the types. As far as the implementation goes, I've had success patching the type locally as follows: type QueryKey = Register extends {
queryKey: infer TQueryKey;
}
? TQueryKey extends Array<unknown> // ensures that we can't override the type to something other than an `Array`
? TQueryKey
: ReadonlyArray<unknown>
: ReadonlyArray<unknown>; And using the following in a import '@tanstack/react-query';
declare module '@tanstack/react-query' {
interface Register {
queryKey: [AppArea | (string & {}), ...ReadonlyArray<unknown>]; // provides intellisense, but does not raise a type error if the first item doesn't conform to `AppArea`
}
} Would be curious to hear from the maintainers if they think this is a good idea, and if so I'd be happy to open a PR. If not, I'm also keen to find out if there is a better approach! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
yeah I think we could do that, should be non-breaking. If you want to file a PR, please do 🙌 |
Beta Was this translation helpful? Give feedback.
@TkDodo great! I've just opened a PR for it: #8521