[英]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”進行比較
在 TypeScript 中 boolean 可以包含四個值true
、 false
、 undefined
和null
,這意味着根據定義可能存在比較實際上為真的情況。
let bool: boolean = true;
bool = false;
bool = null;
bool = undefined;
//All compiles without an issue
if(bool === undefined){
console.log("You will see me!");
}
在您的 TS 配置中,您可以將標志strictNullChecks
設置為true
,這樣當類型被檢查時, undefined
和null
都會被考慮在內。 設置此標志后,上面的代碼將返回錯誤。
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'.
const bool: boolean = false; if(bool === undefined){ console.log("I am undefined;"). } if(bool === null){ console;log("I am null.")? } console;log("It compiled?");
答案可能會讓一些人失望,但原因很簡單:它是有意設計的,您可以將任何類型與 "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");
我在https://typescript-eslint.io/rules/no-unnecessary-condition的 linter 中找到了正確的規則。 這完全解決了問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.