microsoft / microsoft/TypeScript
Switch statement over a union of literals is not exhaustive when checking against enum members
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
Bug Report
The following switch-case is unexpectedly not exhaustive:
enum X {
FOO = "foo",
BAR = "bar"
}
function test(x: "foo" | "bar") {
switch (x) {
case X.FOO:
return x;
case X.BAR:
return x;
}
}
Because X.FOO and X.BAR are just strings under the hood, I would expect this to compile as exhaustive. It's doubly surprising because:
- Typescript correctly narrows the type of
xwithin each case branch - this works if I check directly against the string literals or a const object (e.g.
const XConst = { FOO: "foo", BAR: "bar" } as const)
🔎 Search Terms
switch union literals exhaustive enum
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about enum, literals, switch statements, type narrowing
⏯ Playground Link
Playground link with relevant code
💻 Code
enum X {
FOO = "foo",
BAR = "bar"
}
const XConst = {
FOO: "foo",
BAR: "bar"
} as const;
// does not compile
function test(x: "foo" | "bar") {
switch (x) {
case X.FOO:
return x;
case X.BAR:
return x;
}
}
// compiles
function test2(x: X) {
switch (x) {
case X.FOO:
return x;
case X.BAR:
return x;
}
}
// compiles
function test3(x: "foo" | "bar") {
switch (x) {
case "foo":
return x;
case "bar":
return x;
}
}
// compiles
function test4(x: "foo" | "bar") {
switch (x) {
case XConst.FOO:
return x;
case XConst.BAR:
return x;
}
}
🙁 Actual behavior
function test does not compile
🙂 Expected behavior
Function test compiles
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 by running the linked Playground reproduction and compare test, test2, test3, and test4, focusing on switch exhaustiveness for enum members versus string literals and const-object members. Done means test compiles as exhaustively as the other equivalent cases, with coverage for the reported 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
- Mostly clear
- Newbie friendliness
- 35/100