【发布时间】: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 更新了
-
在这些情况下,是否允许比较对类型安全没有影响。编译器仍然在生成的真实代码分支中将值的类型缩小为
never:tsplay.dev/w17jGm -
@jsejcksn 看起来很糟糕,没有解决方案吗?
标签: javascript typescript eslint typescript-typings tslint