【问题标题】:Why TypesScript allows an invalid comparison - boolean === undefined?为什么 TypesScript 允许无效比较 - boolean === undefined?
【发布时间】:2022-11-22 22:04:51
【问题描述】:

面对TS的怪异行为。

const isItLanding = false;

if (isItLanding === undefined) { // valid
  return ...;
}

但在这儿

const isItLanding = 1;

if (isItLanding === 'undefined') { // error
  return ...;
}

为什么 TS 不确保不会写入无效比较?我怎样才能改变这种行为?

我的 TS 配置如下所示:

{
  "compilerOptions": {
    "strict": true,
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "importsNotUsedAsValues": "error",
    "allowSyntheticDefaultImports": true,
    "incremental": true,
    "tsBuildInfoFile": ".next/cache/.tscache/",
    "jsx": "preserve",
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"],
      "test-utils": ["./src/client/test-utils"]
    }
  },
  "exclude": ["node_modules", "cypress"]
}

【问题讨论】:

  • 你的 tsconfig 是什么样的?您可能没有启用某些严格的设置。
  • 无论是否启用严格设置,他都不应该将前两个结果视为有效。或者这可能吗?
  • @yuriy636 更新了
  • 在这些情况下,是否允许比较对类型安全没有影响。编译器仍然在生成的真实代码分支中将值的类型缩小为nevertsplay.dev/w17jGm
  • @jsejcksn 看起来很糟糕,没有解决方案吗?

标签: javascript typescript eslint typescript-typings tslint


【解决方案1】:

简短回答:TypeScript 有意允许将任何类型与“null”或“undefined”进行比较

这是允许的,因为布尔值可以是未定义的

在 TypeScript 中,布尔值可以包含四个值 truefalseundefinednull,这意味着根据定义可能存在比较结果为真的情况。

let bool: boolean = true;
bool = false;
bool = null;
bool = undefined;
//All compiles without an issue

if(bool === undefined){
   console.log("You will see me!");
}

如何保证boolean只能为true或false?

在您的 TS 配置中,您可以将标志 strictNullChecks 设置为 true,这样当类型被选中时,undefinednull 将被考虑在内。 设置此标志后,上面的代码将返回错误。

let bool: boolean = true;
bool = false;
bool = null; //Error > Type 'null' is not assignable to type 'boolean'.
bool = undefined; //Error > Type 'undefined' is not assignable to type 'boolean'.

为什么在将标志比较更改为 null 或 undefined 后仍然允许?

考虑下面的代码:
const bool: boolean = false;

if(bool === undefined){
   console.log("I am undefined!");
}
if(bool === null){
   console.log("I am null!");
}

console.log("It compiled?");

为什么这些 if 语句都不返回错误,即使它们始终为 false?

答案可能会让一些人失望,但原因很简单:它是有意设计的,您可以将任何类型与“null”或“undefined”进行比较.这就是语言的构造方式,即允许防御性编程。如果有足够的需求,将来可能会改变,但我个人认为永远不会。

if(12 === undefined){
   console.log("impossible isn't it?");
}
if("ab" === null){
   console.log("no way it will ever be true!");
}
if(false === undefined){
   console.log("never ever");
}

/*
if(12 === "ab") 
^this would error as comparison to different types is allowed only with null and undefined
*/

console.log("Yet, it will indeed compile");

【讨论】:

    【解决方案2】:

    我在 https://typescript-eslint.io/rules/no-unnecessary-condition 的 linter 中找到了正确的规则。 这完全解决了问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多