microsoft / microsoft/TypeScript
ES6 Class: `asserts this is Type` raises error when variable containing instance is type narrowed
未关闭
还没有人认领这个 Issue。
Domain: This-Typing
Help Wanted
Possible Improvement
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.4k
- 平均合并
- 1 天 19 小时
- 30 天内合并 PR
- 117
描述
Bug Report
🔎 Search Terms
- Error: "Assertions require every name in the call target to be declared with an explicit type annotation"
- Assertation function as class method
- Type narrowing class and then calling assertation method
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about this
⏯ Playground Link
Playground link with relevant code
💻 Code
class MyClass {
public assertIsMyClass(): asserts this is MyClass {
if (!(this instanceof MyClass)) {
throw new Error('this was not of type MyClass');
}
}
}
const maybeMyClass: MyClass | undefined = new MyClass();
if (maybeMyClass) {
// This fails with error:
// Assertions require every name in the call target to be declared with an explicit type annotation.(2775)
maybeMyClass.assertIsMyClass();
// But if we simply assign to a new variable without the optionality, it's fine:
// this line works because we have narrowed the type through the if statement above
const definitelyMyClass: MyClass = maybeMyClass;
// This raises no error even though it's equivalent to the first attempt
definitelyMyClass.assertIsMyClass();
}
🙁 Actual behavior
Calling the class method assertation function raises error: "Assertions require every name in the call target to be declared with an explicit type annotation.(2775)"
🙂 Expected behavior
It should pass validation and narrow to the type given in the assertation.
This is because it will have this behavior if you simply assign to a new variable with a new type annotation (but which is equivalent to the narrowed type at that point).
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从提供的 Playground 链接开始,在代码示例中重现该诊断,将经过缩窄的变量与显式标注的变量进行比较。跟踪 TypeScript 编译器中的断言调用验证,并为这个类方法场景添加覆盖。完成的标准是缩窄后的调用通过验证,同时现有的断言检查仍然正确。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100