Predict Switch Narrowing Output
Predict Output Medium
Question
What does this code print?
Code
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "square": return s.size ** 2;
}
}
console.log(area({ kind: "square", size: 3 }));
Hint
The shape is a square with size 3. Area = size squared.
Explanation
The discriminated union uses the kind property to narrow the type. Since kind is "square", TypeScript knows s has a size property. area = 3 ** 2 = 9. Output: 9.
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.