Discriminated Union Narrow
Predict Output Medium
Question
What does this code print?
Code
type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
function area(sh: Shape) {
if (sh.kind === "circle") return Math.PI * sh.r ** 2;
return sh.s ** 2;
}
console.log(area({ kind: "square", s: 3 }));
Hint
Discriminant narrows to square, area = 3*3 = 9.
Explanation
The shape has kind "square", so the if branch is skipped. TypeScript narrows sh to { kind: "square"; s: number } in the else branch. Area = s^2 = 3^2 = 9.
Related Resources
Related Lessons
- Unions & Intersections
Learn unions/intersections.
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.