microsoft / microsoft/TypeScript

Discriminating property with never as possible type makes its enclosing object type disappear when narrowing

Open
#60,702 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

🔎 Search Terms

discriminated union never, discriminating property never

🕗 Version & Regression Information

It happens in every version I tried.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.0-dev.20241206#code/C4TwDgpgBAIglgZwMYFUB2cD2aoF4BQAPlAN5QAmiSACgE6ZgBcUaEAbhLQDRQCGzARigBfIqQpU6DZgCIw9MDJ4AjZgCYRYspWRSmUAK5pyEAGZxW5HkmYBmTfhNIANr1rQk2BMCiZm8ZHQsNHx8OFMACkwAOh0aBQBKUnwoXxSoAHoMqAA9AH58YSgIZwRoEnTMdKzcgtEwyIBCGLi9JIrUqtSa-MLi0vLK6uze4SA

💻 Code
type DiscUnion =
| { discProp: never, a: 1 }
| { discProp: "prop", b: 2 }
| { discProp: undefined, c: 3 }

declare const o: DiscUnion

if(o.discProp) {
  o
  // ^? { discProp: "prop"; b: 2; }
} else {
  o
  // ^? { discProp: undefined; c: 3; }
}

if(!o.discProp) {
  o
  // ^? { discProp: undefined; c: 3; }
} else {
  o
  // ^? { discProp: "prop"; b: 2; }
}
🙁 Actual behavior

{ discProp: never, a: 1 } disappears!

🙂 Expected behavior

In the first if, I expect { discProp: never, a: 1 } to be a possible type of o in the else branch. Viceversa, in the second if I expect it to be a possible type of o in the then branch.

Additional information about the issue

No response

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 supplied TypeScript Playground reproduction and run the DiscUnion example as written. Trace narrowing for both if(o.discProp) and if(!o.discProp); the work is done when the { discProp: never, a: 1 } member remains possible in the expected branches without changing the other narrowed members.

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
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.