microsoft / microsoft/TypeScript

Contextual typing doesn't work when mixing up discriminated unions with function variant

オープン
#62,306 コメント 6 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Domain: check: Contextual Types Help Wanted Possible Improvement
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

### 🔎 Search Terms

contextual typing, discriminated unions

### 🕗 Version & Regression Information

- This is the behavior in every version I tried, and I reviewed the FAQ for entries
- Tested with TS 5.4.5 and TS 5.9.2

### ⏯ Playground Link

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAcg9sA6nATgawJYDsDmBVLDOLKAXgCgoqoAfKACnoDcBDAGwFcIAuKLDgLYAjCCgCUZAHxQmcDABMxlanQDey6tQwBnAMrAU2HLwNcA3Bs1QAZll6NWnHlG0GjE0tNkKxFzQF9LNUsdfUNcAH5ea3ZtCD9qW3tmdi5efmFRDy85RQt-C3IAY2JXKGAIVwBGXngkVExcAiISUgYWbKhVAuLS4HLK4AAmWoRkdCNm4jIukL03XBMULgAaSyT2zu7yHpKsMorXAGZR+ommwmm29U1QheMbWIg1zQ36DqkuwN2+gdcAFlO40a+EurVmrzsm0+2x65FAkCgwMmYLIQQhViod3CD1M8UskOSjjSLnunW8eUsgU0wVu8xxUUebDiCSobxSTnSghE4k+FN8O0KewOgwArLxkRcWjMblp6UYlqt1lD3ltvhZhf1DsAAGwShoo6XXOZhBVMuIvRIqj6eL6C3r7LWDADs+vOoKNGLZ1rVgqAA

### 💻 Code

```ts
type NotWorkingUnion =
| ((value: number) => void)
| {
isString: true;
fn: ((value: string) => void);
}
| {
isString?: false;
fn: ((value: number) => void);
};

const test1: NotWorkingUnion = (a) => {}; // Works
const test2: NotWorkingUnion = { // Works
isString: true,
fn: (a) => {}
};
const test3: NotWorkingUnion = { // Works
isString: false,
fn: (a) => {}
};
const test4: NotWorkingUnion = { // Doesn't work!
fn: (a) => {}
};

type WorkingUnion =
| {
isString: true;
fn: ((value: string) => void);
}
| {
isString?: false;
fn: ((value: number) => void);
};

const test5: WorkingUnion = { // Works
isString: true,
fn: (a) => {}
};
const test6: WorkingUnion = { // Works
isString: false,
fn: (a) => {}
};
const test7: WorkingUnion = { // Works
fn: (a) => {}
};
```

### 🙁 Actual behavior

Contextual typing breaks when an union is both discriminated by a field and one of the union variants is just a function

### 🙂 Expected behavior

Contextual typing should correctly work, as the type system should have enough information to discriminate between a function and an object with or without the field

### Additional information about the issue

`strict` mode is enabled.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンク先の TypeScript Playground の例を再現し、test4 と test7、および明示的に判別されたケースを比較します。関数バリアントを含む union をコンテキスト型付けがどのように処理するかを追跡し、その後、判別子が欠落しているケースをカバーする回帰テストを追加して、callback パラメーターが正しく推論されることを確認します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。