如何向“React.useState"添加类型符号? [英] How to add type notation to `React.useState`?

查看:57
本文介绍了如何向“React.useState"添加类型符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有钩子的 React 16.8.3,目前我想输入 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)

使用我当前的代码,modestring 类型,而我想要它的类型是 Mode.Option 也有同样的问题.

With my current code, mode is of type string, when instead I want it of type Mode. Same issue with Option.

如何给 React.useState 添加类型符号?

How to add type notation to React.useState?

推荐答案

React.useState 使用泛型,因此您可以通过这种方式为其添加类型符号:

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)

仅供参考……React.useState 的类型定义:

Just for information ... type definition of React.useState:

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

这篇关于如何向“React.useState"添加类型符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆