TypeScript · Middle · Question 68 of 75

How do you type a generic data-fetching hook?

function useFetch<T>(url: string): { data: T | undefined; error: Error | null } { /* ... */ }
const { data } = useFetch<User[]>('/api/users');

Explanation

The generic only asserts the type. Passing a schema/parser instead lets the hook infer T and check data at runtime.

Further reading

Problem with a question

TypeScript · Middle · question 68

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz