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');- ✓Correct answer: Make the hook generic in the data type and let callers specify it (ideally paired with runtime validation)
- 2Return
any - 3Hooks can't be generic
Explanation
The generic only asserts the type. Passing a schema/parser instead lets the hook infer T and check data at runtime.