Skip to content

Custom hooks with QueryOptions & TypeScript #1195

Answered by fnn
fnn asked this question in Q&A
Discussion options

You must be logged in to vote

Okay, I'm really bad at TypeScript but this is what I did and I think it is working:

const usePost = <T = Post>(id: number, options?: UseQueryOptions<T, any, Post>) =>
  useQuery(["post", id], getPost, options)

And now if I use the custom hook with a select function the data type is correct.

const { data } = usePost(1234, { select: (post) => post.author }); // 'data' is a string

I just don't know why this works. I thought with this solution I always have to pass the type to the custom hook like this:
usePost<string>(1234, { select: (post) => post.author });, but this is not the case..

Replies: 4 comments 13 replies

Comment options

You must be logged in to vote
1 reply
@fnn
Comment options

Comment options

You must be logged in to vote
8 replies
@zakariaelas
Comment options

@TkDodo
Comment options

@piotrpalek
Comment options

@TkDodo
Comment options

@piotrpalek
Comment options

Answer selected by fnn
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
4 replies
@TkDodo
Comment options

@QuyNguyenDev97
Comment options

@shongs27
Comment options

@TkDodo
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
8 participants