microsoft / microsoft/TypeScript

Assertion methods (`asserts this is`) are not CFA'd without error

未关闭
#41,552 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Bug Domain: check: Control Flow
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

TypeScript Version: 4.0.5, 4.1.0-beta, 4.2.0-dev.20201112

Search Terms:

  • Multiple assertion methods
  • "asserts this is"
  • assertion "cfa"

Code

class X<T, Locked extends boolean> {
    public x: null | T | (Locked extends true ? 1 : 2) = null

    public assert<U>(): asserts this is X<U, Locked> { }
    public lock(): asserts this is X<T, true> {}
}

const x: X<string | number, false> = new X<string | number, false>()

x.assert<string>()
// x is X<string, false> here

x.lock()

Expected behavior:

Either:

  • After x.lock(), x is narrowed to X<string, true>
  • Or, the x.lock() line throws at compile-time due to not being CFA'd

Actual behavior:

After x.lock(), x is narrowed to X<string, false> & X<string | number, true>.

Playground Link: https://www.typescriptlang.org/play?ts=4.2.0-dev.20201112#code/MYGwhgzhAEAaA8AVANNAMge2AawKYBNpcAPAF1wDt8YAjDDEXMCgPmgG8BYAKGj+gAOAVxogAlsGjEAXNApCQIaAB9oiFdAAUmHASJlK1aKQBOQ3NAD80AIzRZAJgCU0ALxyFIHj36CR4yUgIXBNSeABVFk0nWSCQ0hhSAAsxGFS4CNQdPHw2dmgAXx9+YVEJaBAsbGjYqHjElLSYBBRjM1w8ou4unmAMCghSKVkEQZMxCgBzDXkAWxoQ1AAzMBBgtncKXAB3DLGJ6dU5hZNl1fXo725iADo40Ph9qainHgB6N6lodNHTA7O1h1oEkQrgrvhcKAwCYLEshBRgKQxP0KlUkFEAG4jJCoOgMJisGLQe4JaAY77NHFtcwsK63So4S7cIA

Analysis:

x being typed as X<string, false> & X<string | number, true> shows that the x.lock() narrows from the original type (X<string | number, false>) instead of the narrowed type at that position (X<string, false>).

If instead a "top-level" assertion function is used the type is properly narrowed:

class X<T, Locked extends boolean> {
    public x: null | T | (Locked extends true ? 1 : 2) = null

    public assert<U>(): asserts this is X<U, Locked> { }
    public lock(): asserts this is X<T, true> {}
}

const x: X<string | number, false> = new X<string | number, false>()

x.assert<string>()
// x is X<string, false> here

declare function lock<T>(v: X<T, boolean>): asserts v is X<T, true>
lock(x)

Playground

This leads me to believe this is an issue with the x.lock() call not being CFA'd, in which case the correct behavior would be to throw ts(2775) on the x.lock() line.

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先运行提供的 TypeScript Playground 复现代码,并比较 x.assert<string>()x.lock() 之后的控制流 narrowing。调查编译器对 asserts this is 方法以及所报告的交叉类型的处理方式。当第二个 assertion 要么 narrowing 为 X<string, true>,要么报告预期的编译时错误,并且该示例具有回归覆盖时,即视为完成。

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

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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