javascript - Hur lägger man till typnotering på `React.useState`?


Jag använder React 16.8.3 med hooks, just nu vill jag skriva React.useState

type Mode = 'confirm' | 'deny'  
type Option = Number | null

const [mode, setMode] = React.useState('confirm')
const [option, setOption] = React.useState(100)

Med min nuvarande kod är mode av typen string, när jag istället vill att den ska vara av typen Mode. Samma problem med Option.

Hur lägger man till typnotation till React.useState?

Svar #1

React.useState använder en generisk typ, så du kan lägga till typnotation till den på detta sätt:

const [mode, setMode] = React.useState<Mode>('confirm')
const [option, setOption] = React.useState<Option>(100)

Bara för information ... typdefinition av React.useState:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

Relaterade artiklar