microsoft / microsoft/TypeScript

Discriminated union containing optional properties and generic types is not narrowed

Open
#55,036 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Possible Improvement
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.