microsoft / microsoft/TypeScript

incorrect inference in union of tuple types

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

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

Domain: check: Type Inference Help Wanted Possible Improvement
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

🔎 Search Terms

tuple type union, inference, discriminator

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Generics.
⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.3#code/C4TwDgpgBAggdgEwDwBUB8UC8UDaAiAQ0TwBooUIAnAW1TTIproF0AoUSKAUQEc6tceCD1Lk2HaAElgAZ1RkA0lAgAPYBEQyoAawggA9gDNyGbPgCWs0QoZVaKHAuZpx4aI3unufdFAA+UNJyKGS6Bsa+AfDI6KyshgCucADGwOb6cFBglBAI5skE6nQAFOo0AFzkdnQAlFAA3qxQzVA5wAmUmWXUrAC+cckZMsBQwJUeSPUE5XAJ1ABGVL1e2bn5hRDFFlZkhKL4wqIADMzMNaxAA

💻 Code
type And<T> = ["and", Term<T>, Term<T>]
type Eq<T> = ["eq", T]
type Its<T, K extends keyof T> = ["its", K, Term<T[K]>]
type Term<T> = Eq<T> | Its<T, keyof T> | And<T>

function predicate<T>(term: Term<T>) {
    return term
}

const t: Term<{a:number}> = predicate(["its", "a", ["eq", 0]])
🙁 Actual behavior

TypeScript complains that Type "a" is not assignable to type number | "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString" | Term<number>. The expected types are a union of number from Eq<number>, Term<T> from And<T> and keyof number from Its<number>. Eq<number> can be ruled out by both length and first element and And<T> by the first element. number was chosen as value of T despite there being a solution that is also clear for the expected return type.

🙂 Expected behavior

TypeScript infers T to be { a: number } (or { a: any } when the return type is not known).

Additional information about the issue

It works when you remove And from Term, moving the "and" to the last index or when modelling something similar using objects instead of tuples. The first element could be used to discriminate the union.

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

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

はじめの一歩

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

調査の方向性

提供された Term、Eq、Its、And 型を使用して、リンク先の TypeScript Playground でタプル共用体の推論失敗を再現します。共用体全体でジェネリックパラメーターを推論する際に、最初のタプル要素がどのように使用されるかを調査します。既存のタプルケースを維持しつつ、例で T が { a: number }(コンテキスト上の戻り値型がない場合は { a: any })として推論されれば完了です。

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

評価

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

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

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