简体   繁体   English

不允许 null 或未定义的 useState 和 TypeScript?

[英]Dont allow null or undefined with useState and TypeScript?

I'm adding TypeScript types to React's useState hook.我将 TypeScript 类型添加到 React 的 useState 挂钩中。

const [checked, setChecked] = React.useState<"checked" | un-checked">(null);

Is it possible to only allow the checked and un-checked values and not null or undefined so that the code above would error?是否可以只允许checkedun-checked值,而不是nullundefined以便上面的代码会出错?

You need to enable "strictNullChecks": true in your tsconfig.json您需要在您的tsconfig.json中启用"strictNullChecks": true

Argument of type 'null' is not assignable to parameter of type '"checked" | 'null' 类型的参数不能分配给 '"checked" 类型的参数 | "un-checked" | “未检查” | (() => "checked" | "un-checked")'. (() => "已检查" | "未检查")'。

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html

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

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