microsoft / microsoft/TypeScript
incorrect inference in union of tuple types
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
🔎 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
💻 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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the tuple-union inference failure in the linked TypeScript Playground using the provided Term, Eq, Its, and And types. Investigate how the first tuple element is used when inferring the generic parameter across the union. Done means the example infers T as { a: number } (or { a: any } without a contextual return type) while preserving the existing tuple cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100