繁体   English   中英

可选用 jsdoc、typescript checkjs (javascript) 反应 useState 类型

[英]optional react useState types with jsdoc, typescript checkjs (javascript)

使用 typescript 的 jsdoc 支持键入以下javascript代码:

const [optionalNumber, setOptionalNumber] = useState(null)

const handleClick = () => {
  setOptionalNumber(42) 
  //          ^-- Argument of type '42' is not assignable to parameter of type 'SetStateAction<null>'
}

我目前解决这个问题的方式可行,但有点难看:

const [optional, setOptional] = useState(
  /** @type {number|null} */ (null)
)

我怎样才能在不使用铸造的情况下做到这一点? 我希望有一种类型的optional null | number null | numbersetOptional仅接受null | number null | number作为参数。

代码框演示了这一点:
https://codesandbox.io/s/optimistic-villani-kbudi?fontsize=14

Assuming that your component relies on the inital state of the optional state being the null value (rather than undefined ), one solution would be to explicitly specify the state hooks type as a union type of both number and null like so:

// Allows initial value to be null, and number to be subsequently set 
const [optional, setOptional] = useState<number | null>(null);

// optional === null

setOptional(42);

或者,如果您的组件没有区分初始optional state 值的undefinednull值,则以下将起作用:

const [optional, setOptional] = useState<number>();

// optional === undefined

setOptional(42);

我认为您可以使用正确的联合类型定义一个初始值并将其传递给useState

它会是这样的:

/**
* @type {number | null}
*/
const initValue = 42;
const [optionalNumber, setOptionalNumber] = useState(initValue)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM