简体   繁体   中英

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?

很简单:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM