Never in Switch
Predict Output Medium
Question
What does this code print?
Code
type Color = "red" | "green" | "blue";
function fn(c: Color) {
switch (c) {
case "red": return 1;
case "green": return 2;
case "blue": return 3;
default: const _: never = c; return 0;
}
}
console.log(fn("green"));
Hint
Exhaustive switch with never check; "green" returns 2.
Explanation
The switch handles all three colors. The default case assigns c to never (exhaustiveness check — if a new color is added, this would error). fn("green") matches case "green" and returns 2.
Related Resources
Related Lessons
- Type Narrowing
Learn narrowing.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.