MediumType Inference💻 Output Question

Discriminated union narrowing via switch

💡

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.

What does this output?

// 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 });

Correct Output

area:78.54
area:16.00
area:18.00

Why this output?

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.

More Type Inference Output Questions

Easytypeof narrowing determines which branch runsMediumConst assertion — literal type vs widened typeHardReturnType inference — function return shapes

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz