5

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?

Radex
  • 7,815
  • 23
  • 54
  • 86

1 Answers1

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

GibboK
  • 71,848
  • 143
  • 435
  • 658