反应useState钩子输入错误

时间:2020-06-16 07:20:34

标签: reactjs typescript react-native expo

当我尝试使用没有默认值的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,
  }
}

1 个答案:

答案 0 :(得分:1)

您在 compilerOptions

中缺少"strictNullChecks": true

在严格的null检查模式下,nullundefined值不在每种类型的域中,只能分配给自己和any(一个例外是{{ 1}}也可分配给undefined)。因此,尽管voidT 在常规类型检查模式下被视为同义词(因为T | undefined 被认为是任何类型的子类型 { {1}},它们在严格类型检查模式下是不同的类型,并且只有undefined允许T的值。 T | undefinedundefined的关系也是如此。

更多信息here