不允许使用 useState 和 TypeScript 为 null 或 undefined 吗?

Dont allow null or undefined with useState and TypeScript?

我正在将 TypeScript 类型添加到 React 的 useState 挂钩。

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

是否可以只允许 checkedun-checked 值而不允许 nullundefined 以便上面的代码出错?

您需要在 tsconfig.json

中启用 "strictNullChecks": true

Argument of type 'null' is not assignable to parameter of type '"checked" | "un-checked" | (() => "checked" | "un-checked")'.

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