【问题标题】:React useState hook gets typed incorrectlyReact useState 钩子输入错误
【发布时间】: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&lt;Color | undefined&gt;(); 但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&lt;Color&gt;(undefined); 类型的color 仍然只是Color 而不是Color | undefined。
  • 但是这会破坏不是吗? undefined.toLocaleLowerCase();
  • 在运行时无论如何它都会中断。我希望 typescript 在实际运行代码之前捕获错误。
  • @RedBaron 接受 Aleksey L. 的回答,解释了问题所在以及如何解决。

标签: reactjs typescript react-native expo


【解决方案1】:

compilerOptions

中缺少"strictNullChecks": true

在严格的空检查模式下,null 和 undefined 值不在每个类型的域中,并且只能分配给它们自己和 any(一个例外是 undefined 也可以分配给 @ 987654327@)。因此,虽然T 和T | undefined 在常规类型检查模式下被认为是同义词(因为undefined 被认为是任何 T 的子类型),但它们是严格类型检查模式下的不同类型,并且只有T | undefined 允许undefined 值。 T与T | null的关系也是如此。

更多信息here.

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2023-03-19
    • 2021-02-07
    • 1970-01-01
    • 2020-04-29
    • 2021-04-14
    • 1970-01-01
    • 2020-06-03
    • 2021-05-23
    相关资源
    最近更新 更多