microsoft / microsoft/TypeScript
Generic type unnarrowed by `switch...case`
オープン
まだ誰も着手していません。
In Discussion
Suggestion
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
Bug Report
🔎 Search Terms
- narrowing of generic types
- exhaustive switch case
🕗 Version & Regression Information
Theoretically this should be fixed by:
- https://github.com/microsoft/TypeScript/issues/13995
- https://github.com/microsoft/TypeScript/pull/43183
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.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされた TypeScript Playground の再現コードから始め、switch の case 内のジェネリックな return で報告されたエラーを確認します。switch 節に対するコンパイラのジェネリック型の絞り込みを追跡し、case によって TagName が絞り込まれ、期待されるコードが assertion なしで型チェックを通過することを示すリグレッションテストを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 38/100