Custom hooks in TypeScriptSeptember 25, 2020
I learned a cool TypeScript tip while I was trying to write a hook to manage the state of a
My hook was pretty straightforward. It looked something like this:
I tried to use the hook, and I got a typescript error:
The main part of the TypeScript error that we need to focus on is this:
Not all constituents of type 'string | ((value: string) => void)' are callable.
Because we are returning a tuple from the
useRadioList hook, and not explicitly typing the return type of the hook, TypeScript infers that it's an array, which can contain an infinite number of elements.
TypeScript can't tell if
updateSelectedValue is a string or a function.
There are two ways to fix this problem:
- I can be explicit about the return type of the
- I can pair a type assertion with the
Either way, TypeScript now knows that useRadioList returns an array with two elements in it. The first one is always a string, and the second one is always a function.
Do you want design systems tips and tricks sent to your inbox?