Skip to main content
TypeScript Output Prediction Hard +35 XP

Discriminated Union

How does TypeScript narrow this union?

TypeScriptRead-only
type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };
function area(s: Shape) {
  if (s.kind === "circle") return Math.PI * s.r ** 2;
}

What is the output?

Show answer and explanation

Answer: By checking the kind literal property

Discriminated unions use a common literal property (kind) to narrow the type. TypeScript knows s.r exists only in the circle branch.

Hint: The 'kind' field is the discriminant.

What this challenge tests

Output Prediction in TypeScript: discriminated-unions, narrowing.

Related challenges