microsoft / microsoft/TypeScript
Discriminated union containing optional properties and generic types is not narrowed
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
Bug Report
I would have expected doesNotNarrow (below) to also be able to narrow x.b to NonUndefined<B>.
🔎 Search Terms
generic, narrow, discriminated, union, optional
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed all the FAQ for entries.
⏯ Playground Link
Playground link with relevant code
💻 Code
type NonUndefined<T> = T extends undefined ? never : T
type X<A, B> = { a: NonUndefined<A>, b?: never } | { a?: never, b: NonUndefined<B> }
function doesNarrow(x: X<number, number>) {
if (x.a === undefined) {
const y = x.b
// ^? number
}
}
function doesNotNarrow<A extends number, B extends number>(x: X<A, B>) {
if (x.a === undefined) {
const y = x.b
// ^? NonUndefined<B> | undefined
}
}
🙁 Actual behavior
x.b was not narrowed.
🙂 Expected behavior
I expected x.b to be narrowed because if x.a is undefined, then x must be the latter part of the discriminated union because x.a can only be undefined there. TypeScript seems to be able to work that out when the type parameters are constant/non-generic (see doesNarrow), but for some reason it's not able to work it out for the generic case (even though NonUndefined should make it feasible).
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
Start with the linked TypeScript Playground and compare the narrowing in doesNarrow with doesNotNarrow. Investigate the generic discriminated-union narrowing path using the provided X, NonUndefined, and optional-property example. Done means x.b is narrowed to NonUndefined in the generic case without regressing the non-generic behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100