TypeScript · Junior · Question 44 of 75

What is a union with a common discriminant field?

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; size: number };

Explanation

The check if (shape.kind === 'circle') narrows the type, and shape.radius is available inside. It's the main way to model states: { status: 'loading' } | { status: 'success'; data } | { status: 'error'; error }.

Further reading

Problem with a question

TypeScript · Junior · question 44

Test yourself

Take the TypeScript · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz