microsoft / microsoft/TypeScript
This narrowing typeguard effect bleeds into subsequent statments on a type with bivariant type-parameter
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
TypeScript Version: 3.4.0-dev.201xxxxx (although 3.3 is also impacted)
Search Terms: this type guards
If we create a type-guard that narrows this on a type that has a type-parameter that is present only in a bivariant position, the effect of the type guard persists outside of the guarded block.
Code
type GetKnownKeys<G> = G extends GuardedMap<infer KnownKeys> ? KnownKeys: never;
interface GuardedMap<KnownKeys extends string> {
get(k: KnownKeys): number;
has<S extends string>(k: S): this is GuardedMap<S | GetKnownKeys<this>>;
}
declare let map: GuardedMap<never>;
map.get('bar') // err, as expected
if (map.has('foo')) {
map.get('foo').toExponential(); // ok as expected
if(map.has('bar'))
{
map.get('foo').toExponential(); // ok as expected
map.get('bar').toExponential(); // ok as expected
}
map.get('bar').toExponential(); /// OK!?!?! WHY ?!
}
map.get('bar') // OK ?!
Expected behavior:
Type guard only impacts the guarded block.
Actual behavior:
The effect of the type guard bleads into all subsequent statements. (marked with OK!?!?! and OK?!)
Note: With strictFunctionTypes on, declaring get as get: (k: KnownKeys) => number; makes the code work as expected.
Playground Link: link
Related Issues: Similar to #14817
Found this while playing with a solution for #9619
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
使用提供的 GuardedMap 示例,在链接的 TypeScript Playground 中重现 narrowing 泄漏。跟踪编译器对 this 类型守卫和双变类型参数的控制流处理;完成的标准是 narrowing 仍限制在受守卫的代码块中,并且代码块之后的 map.get('bar') 会被拒绝,同时包含回归覆盖测试。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 38/100