admin管理员组

文章数量:1353584

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?

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?

Share Improve this question asked Mar 5, 2019 at 10:10 RadexRadex 8,64724 gold badges61 silver badges97 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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>>];

本文标签: javascriptHow to add type notation to ReactuseStateStack Overflow