Reputation: 8577
I am using React 16.8.3 with hooks, currently I want to type React.useState
type Mode = 'confirm' | 'deny'
type Option = Number | null
const [mode, setMode] = React.useState('confirm')
const [option, setOption] = React.useState(100)
With my current code, mode
is of type string
, when instead I want it of type Mode
. Same issue with Option
.
How to add type notation to React.useState
?
Upvotes: 5
Views: 4349
Reputation: 73908
React.useState
uses a generic, so you can add type notation to it in this in this way:
const [mode, setMode] = React.useState<Mode>('confirm')
const [option, setOption] = React.useState<Option>(100)
Just for information ... type definition of React.useState
:
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Upvotes: 10