Hint
Discriminated unions use a literal-type "tag" field to narrow the type in each branch. TypeScript automatically knows which properties are available after each case — this is exhaustiveness checking in action.
// Simulates TypeScript discriminated union narrowing
function processShape(shape) {
switch (shape.kind) {
case 'circle':
// Narrowed to circle — radius available
console.log('area:' + (Math.PI * shape.radius ** 2).toFixed(2));
break;
case 'square':
// Narrowed to square — side available
console.log('area:' + (shape.side ** 2).toFixed(2));
break;
case 'rectangle':
console.log('area:' + (shape.width * shape.height).toFixed(2));
break;
}
}
processShape({ kind: 'circle', radius: 5 });
processShape({ kind: 'square', side: 4 });
processShape({ kind: 'rectangle', width: 3, height: 6 });area:78.54 area:16.00 area:18.00
Explanation: Each switch case narrows the type. After case "circle", shape is { kind: "circle"; radius: number } and shape.radius is safe to access.
Key Insight: Discriminated unions use a literal-type "tag" field to narrow the type in each branch. TypeScript automatically knows which properties are available after each case — this is exhaustiveness checking in action.