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 };- ✓Correct answer: A discriminated union: TS narrows the type by
kindinswitch/if - 2An error: a union can't use identical property names
- 3An intersection of two objects with a
kindproperty
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 }.