Custom hooks in TypeScript

Mae Capozzi · September 25, 2020What to do when TypeScript complains about the return type of your custom hook.

I learned a cool TypeScript tip while I was trying to write a hook to manage the state of a RadioList component.

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:

  1. I can be explicit about the return type of the useRadioList hook

  1. I can pair a type assertion with the const keyword

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.

Continue Reading

aiobservabilitydeveloper-tools

AI agents removed the friction from writing telemetry

I used to avoid adding telemetry because it felt like tedious busywork. Now with Claude handling the OpenTelemetry boilerplate, I'm instrumenting everything.

Read Post