簡體   English   中英

為什么 TypesScript 允許無效比較 - boolean === undefined?

[英]Why TypesScript allows an invalid comparison - boolean === undefined?

面對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"]
}

簡短回答:TypeScript 有意允許將任何類型與“null”或“undefined”進行比較

這是允許的,因為 boolean 可以是未定義的

在 TypeScript 中 boolean 可以包含四個值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只能為真或為假?

在您的 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 或未定義后仍然允許?

考慮下面的代碼:
 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");

這種行為是故意的。 請參閱#14764#11920中有關它的討論。


簡而言之:為了“防御性編程” ,檢查是否有undefinednull是必需的。

當值可能來自非 TypeScript 用戶時,應該能夠測試輸入是否有效。

考慮這樣的 function:

function fn(x: string) {
  if (x === undefined) throw new Error('x cannot be undefined');
}

使用 JavaScript 的人完全有可能調用此 function 並使用可能undefined的值。 出現不允許比較的編譯時錯誤會很煩人。

我在https://typescript-eslint.io/rules/no-unnecessary-condition的 linter 中找到了正確的規則。 這完全解決了問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM