CodePark/ questions / TypeScript with React
START PRACTICINGPRACTICE
Frontend question · TypeScript › TypeScript with React

What is the return type of useToggle?

function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn((v) => !v);
  return [on, toggle];
}
(boolean | (() => void))[]

The answer is (boolean | (() => void))[]. TypeScript infers an array literal as an array of the union of its elements, not as a tuple. So callers cannot tell on and toggle apart.

[boolean, () => void] is the tempting wrong answer, because it is what the hook means to return. To get a tuple, return [on, toggle] as const, which gives readonly [boolean, () => void].