microsoft / microsoft/TypeScript
Compiler warning for always true/false strict inequality expression
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
Search Terms
type guard warning if always true false non-identity inequality
Suggestion
The compiler should emit a warning if it can determine that an expression using a strict inequality check (!==) always returns true or false. It already does this for strict equality checks (===).
Use Cases
Like the warnings for the strict equality check, it helps identifying unreachable code blocks or unnecessary if blocks which can get introduced during refactoring of existing code or during carefree creation of new code.
Examples
The following function definition emits an error ("This condition will always return 'false' since the types '"abc"' and '"xyz"' have no overlap."):
function fn(p: "abc") {
if (p === "xyz") {
}
}
But this function definition compiles just fine (a possible error message could be "This condition will always return 'true' since the types '"abc"' and '"abc"' overlap completely":
function fn2(p: "abc") {
if (p !== "abc") {
}
}
It even correctly type-guards the type of p inside the if block (it becomes never).
Two other scenarios which trigger this non-warning, but could be harder to detect:
// typeof checks
function fn3(p: string) {
if (typeof p !== "string") {
}
}
// the length of a tuple
function fn4(p: []) {
if (p.length !== 0) {
}
}
The last example doesn't type-guard the value of p correctly to never even though p.length is correctly of type 0, maybe this is a separate feature request.
Problems / Discussion Points
- I'm not sure whether this qualifies as a breaking change, since it introduces a warning for code constructs which compile totally fine at the moment.
- This could be extended for other checks as well (e.g. for the
</<=and>/>=operators) even though this would be pretty edge-casey.
Checklist
My suggestion meets these guidelines:
- (Unsure) This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
未指定文件、测试或编译器入口点。首先定位现有的严格相等检查诊断,并比较严格不等、typeof 和元组长度表达式的分析方式。完成标准是:为可证明始终为真或始终为假的 !== 条件添加诊断,同时不改变生成的 JavaScript。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100