TKoL
TKoL

Reputation: 13892

How to specify type of UseState output in typescript react

I've got a variable whose initial value I want to be null, but I want to be able to set it as a number as well.

const [intervalId, setIntervalId] = useState(null);

When I write setIntervalId(2); in my code later, it complains that argument type number is not assignable to SetActionState<null>.

What's the proper way to define such a variable in React?

Upvotes: 1

Views: 94

Answers (1)

jmk
jmk

Reputation: 1610

Pretty simple:

const [intervalId, setIntervalId] = useState<null | number>(null);

Upvotes: 3

Related Questions