microsoft / microsoft/TypeScript
Discriminated union narrowing fails when use template literal types as tag
未关闭
还没有人认领这个 Issue。
Awaiting More Feedback
Suggestion
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.4k
- 平均合并
- 1 天 19 小时
- 30 天内合并 PR
- 117
描述
TypeScript Version: 4.2.0-dev.20201211
Search Terms: narrowing, discriminated union, template literal types
Code
type Types<T extends string> = {
one: `${T}/one`;
two: `${T}/two`;
}
type OneObj<T extends string> = {
type: Types<T>["one"];
one: string;
}
type TwoObj<T extends string> = {
type: Types<T>["two"];
two: string;
}
type OneOrTwoObj<T extends string> = OneObj<T> | TwoObj<T>
declare function acceptsOneObj<T extends string>(oneObj: OneObj<T>): void;
declare function acceptsTwoObj<T extends string>(twoObj: TwoObj<T>): void;
function f<T extends string>(oneOrTwoObj: OneOrTwoObj<T>, types: Types<T>){
switch(oneOrTwoObj.type){
case types.one:
return acceptsOneObj(oneOrTwoObj); // Error: Argument of type 'OneOrTwoObj<T>' is not assignable to parameter of type 'OneObj<T>'.
case types.two:
return acceptsTwoObj(oneOrTwoObj); // Error: Argument of type 'OneOrTwoObj<T>' is not assignable to parameter of type 'OneObj<T>'.
}
}
Expected behavior:
oneOrTwoObj should be narrowed to OneObj or TwoObj in function f
Actual behavior:
narrowing fails
Playground Link:
playground
Related Issues:
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从链接的 TypeScript Playground 复现和泛型函数 f 开始,重点关注针对 oneOrTwoObj.type 的 switch 如何处理模板字面量类型。确认当前行为,然后跟踪判别联合收窄的类型检查路径。完成的标准是每个 switch 分支都将 oneOrTwoObj 收窄为对应的 OneObj 或 TwoObj,使 acceptsOneObj 和 acceptsTwoObj 调用通过类型检查。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100