【发布时间】:2020-06-16 07:20:34
【问题描述】:
当我尝试在没有默认值的情况下使用 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,
}
}
【问题讨论】:
-
为什么不使用默认值?
-
因为如果我没记错
undefined是默认值,如果没有提供其他值。但是,即使我尝试const [color, setColor] = useState<Color>(undefined);类型的color仍然只是Color而不是Color | undefined。 -
但是这会破坏不是吗?
undefined.toLocaleLowerCase(); -
在运行时无论如何它都会中断。我希望 typescript 在实际运行代码之前捕获错误。
-
@RedBaron 接受 Aleksey L. 的回答,解释了问题所在以及如何解决。
标签: reactjs typescript react-native expo