3

I am using useQuery hook from react-query and when I try to access my keys inside of query-function i.e., 2nd argument for useQuery, I am facing an issue with typescript it's complaining on this statement

const postId = queryKey[1].id as any

that

Property 'id' does not exist on type 'string | { id: string | undefined; comments: boolean; }'.
  Property 'id' does not exist on type 'string'.ts(2339)

Everything works fine, I have a defined in postId, the request is sent to the server and I get a response back, problem is with typescript, I even tried to assert the type but doesn't work

  const { data } = useQuery(['post', { id: post?.id, comments: true }], async ({ queryKey }) => {
    const postId = queryKey[1].id as any
     const { data } = await axios.get(`/post/${postId}`, {
       headers: {
         Authorization: `Bearer ${user?.idToken}`,
       },
     })
     return data
  })

Is there any typescript way to solve this ?

1 Answer 1

2

Types of the queryKey flow through very well in react-query, but you have to give your key an explicit type. If you just do:

['post', { id: post?.id, comments: true }]

Typescript will try to infer the best possible thing, which is an Array of string or object. Every position can have a string or an object as far as Typescript is concerned, so you can’t access the second element like that. You need to give your key a more concrete type. The easiest way is to use const assertions:

['post', { id: post?.id, comments: true }] as const

With that, typescript will infer a readonly Tulpe where the first Element is a string and the second element is an object. With that, your access should work just fine.

Sign up to request clarification or add additional context in comments.

2 Comments

What if query function is somewhere in the different file? E.g. const { data } = useQuery(['post', { id: post?.id, comments: true }], getPost). How to get proper types inside getPost?
@Skay Try explicitly typecasting it inside getPost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.