lukemorales / query-key-factory

A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query
https://www.npmjs.com/package/@lukemorales/query-key-factory
MIT License
1.16k stars 32 forks source link

Problems with types inferring when using context queries #86

Closed viktorkrepak closed 6 months ago

viktorkrepak commented 6 months ago

Hello! we recently migrated to v5 Tanstack and updated query-key-factory package accordingly, but after this update we had to change our key factories, because it seems Tanstack type system has evolved. But now when I describe context queries (see example ⬇️ ) CleanShot 2024-02-24 at 22 56 12@2x

and then try to use them - typescript acts weird (but the code works though, I temporary added @ts-ignore to not see the error) CleanShot 2024-02-24 at 22 56 29@2x

If I change my key params like that (duplicate some args from the parent key ⬇️ ) CleanShot 2024-02-24 at 22 56 49@2x

the TS error disappears (TS infers a proper type) - CleanShot 2024-02-24 at 22 57 11@2x

but it forces me to duplicate a bunch of params and then It's harder to destructure them from the key array. I'd like to help with solving this issue, but maybe I'm doing smth wrong on my side (in my code)? Would be grateful for any help or a piece of advice

lukemorales commented 6 months ago

@viktorkrepak thanks for opening the issue, I was able to duplicate it and the reason is because params can be undefined, so when you add just queryKey: [params] the type system is not inferring correctly, but if you do queryKey: [params!], you will notice it works as expected. I'll see if I can get a fix out soon, but in the mean time, you could "fix" it by assigning a default value to your optional argument (params: Params | ComputedRef<Params | undefined> = {})

lukemorales commented 6 months ago

@viktorkrepak v1.3.4 has been released with a fix, could you confirm if that solves your issue?

viktorkrepak commented 6 months ago

@lukemorales just updated the version, types looks good, no errors anymore, works like a charm! Thanks a lot for your quick response and wonderful library, it makes our life much easier when we work with Tanstack keys!