microsoft / microsoft/TypeScript

Flag 'instanceof' expressions that are provably always true or false

未关闭
#32,801 6 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

Suggestion

When refactoring code, TypeScript is generally very good at finding and reporting situations where existing code will break due to type changes. This allows "refactoring with confidence". This isn't surprising given that one of the primary goals of TypeScript is to "statically identify constructs that are likely to be errors".

There's one common case where TypeScript is "blind" and doesn't report errors when types are refactored. This case involves the use of the 'instanceof' operator. This operator can be used in situations where it makes no sense -- e.g. where the type specified on the LHS has no possible relation to the type specified on the RHS.

To help developers avoid this common programming error, I propose that TypeScript report an error for any 'instanceof' expression that is provably always true or false at compilation time. Any such expression will likely be unintended by the programmer and should be flagged as errors. At best, such operations represent unnecessary code that imposes runtime overhead.

Example

// ClassB is a subclass of ClassA.
class ClassA {}
class ClassB extends ClassA {}

// ClassC has nothing to do with either
// ClassA or ClassB.
class ClassC {
    method1() {}
}

function function1(param1: ClassB) {
    // Static analysis can prove this expression
    // will always evaluate to false. It's a common
    // source of programming errors, especially during
    // refactoring.
    if (param1 instanceof ClassC) {
        // This call isn't even valid given that param1
        // was declared as type ClassB.
        param1.method1();
    }

    // Static analysis can prove this expression will
    // always evaluate to true, so at best it's unnecessary
    // runtime overhead and more commonly is a behavior
    // that is unintended by the programmer.
    if (param1 instanceof ClassA) {
        // ...
    }
}

Are there any legitimate uses of 'instanceof' where the result is statically provable to be true or false in all cases? I can't think of any, but it's possible I'm overlooking some specialized cases. If there are, this check could be added as an optional compiler switch to preserve the current behavior.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先检查 issue 中的 ClassA、ClassB 和 ClassC 示例,以及 TypeScript 编译器中现有的 instanceof 类型检查行为。确定应如何诊断始终为真的情况和始终为假的情况,包括任何合理的例外情况。完成标准是:编译器报告预期的情况,示例得到覆盖,并保留有效的 instanceof 用法。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
28/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。