当我尝试使用没有默认值的useState
钩子时,将其输入错误。它在可能的类型中不包括undefined
。例如在组件波纹管中:
type Color = 'blue' | 'yellow' | 'red';
const MyComponent: React.FC = () => {
const [color, setColor] = useState<Color>();
color.toLocaleLowerCase();
return null;
};
color
的类型为Color
,因此color.toLocaleLowerCase()
不会引发任何打字错误,即使实际上color
也可以是未定义的(当然,会导致运行时错误)。
我什至尝试将undefined
明确指定为可能的类型:const [color, setColor] = useState<Color | undefined>();
,但是color
的键入方式仍与Color
一样。
我几乎可以肯定这曾经有用。还有其他人遇到类似问题吗?
某些依赖项:
"react": "16.9.0",
"expo": "^37.0.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
"@babel/preset-typescript": "^7.8.3",
"@typescript-eslint/parser": "^2.28.0",
"@typescript-eslint/eslint-plugin": "^2.28.0",
"typescript": "^3.8.3",
我的tsconfig.json
:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "react-native",
"lib": ["dom", "esnext"],
"moduleResolution": "node",
"noEmit": true,
"skipLibCheck": true,
"noImplicitAny": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"isolatedModules": false,
"baseUrl": "./",
"sourceMap": true,
}
}
答案 0 :(得分:1)
您在 compilerOptions
中缺少"strictNullChecks": true
在严格的null检查模式下,
null
和undefined
值不在每种类型的域中,只能分配给自己和any
(一个例外是{{ 1}}也可分配给undefined
)。因此,尽管void
和T
在常规类型检查模式下被视为同义词(因为T | undefined
被认为是任何类型的子类型 { {1}},它们在严格类型检查模式下是不同的类型,并且只有undefined
允许T
的值。T | undefined
与undefined
的关系也是如此。
更多信息here。