microsoft / microsoft/TypeScript

Generic type unnarrowed by `switch...case`

未关闭
#43,873 10 条评论 5 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Bug Report

🔎 Search Terms
  • narrowing of generic types
  • exhaustive switch case
🕗 Version & Regression Information

Theoretically this should be fixed by:

Similar issue:

I'm trying against the latest beta: 4.3.0-pr-43183-11 / 15fae38b39a370f1f597606e552dd40998a1ac49.

⏯ Playground Link

Playground link with relevant code

💻 Code
interface TopLevelElementMap {
	"a": HTMLElement;
	"b": HTMLElement;
}

interface ElementAttributes {}

interface ElementAttributesMap {
	"a": ElementAttributes;
	"b": ElementAttributes;
}

class Element<TagName extends keyof TopLevelElementMap> {
	protected attributes: ElementAttributesMap[TagName] = {};

	public constructor(type: TagName) {}
}

const ElementTagNameMap = {
	"a": function(): Element<"a"> {
		return new Element("a");
	},
	"b": function(): Element<"b"> {
		return new Element("b");
	}
};

function createPrimitive<TagName extends keyof typeof ElementTagNameMap>(tagName: TagName) {
	switch (tagName) {
		case "a":
			return function(): Element<TagName> {
				//
				// [?] Shouldn't `tagName` get narrowed to just "a"?
				//
				return ElementTagNameMap[tagName]();
			};

		case "b":

		default:
			throw new Error("Unrecognized element `" + tagName + "`.");
	}
}

const a = createPrimitive("a");
const b = createPrimitive("b");

As a workaround I can assert as Element<TagName> on the inner-most return statement to silence the error.

🙁 Actual behavior
Type 'Element<"a"> | Element<"b">' is not assignable to type 'Element<TagName>'.
  Type 'Element<"a">' is not assignable to type 'Element<TagName>'.
    Type '"a"' is not assignable to type 'TagName'.
      '"a"' is assignable to the constraint of type 'TagName', but 'TagName' could be instantiated with a different subtype of constraint '"a" | "b"'. (2322)
🙂 Expected behavior

TagName should be narrowed to one of the possible values dictated by the case clause.

贡献指南

打开贡献指南

从这里开始

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

调研方向

从链接的 TypeScript Playground 复现开始,确认 switch case 内泛型返回值上报告的错误。跟踪编译器针对 switch 子句的泛型类型收窄,然后添加回归测试覆盖,表明 case 会收窄 TagName,并且预期代码无需 assertion 即可通过类型检查。

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

评估

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

把新 issue 发到你的邮箱

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