What is a Discriminated Union in TypeScript, and how do you implement it?
Instruction: Describe the concept of Discriminated Union and provide a code example.
Context: This question tests the candidate's knowledge of advanced union types in TypeScript, specifically Discriminated Unions, and their use in creating type-safe code.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
A discriminated union connects a literal tag with the fields belonging to that variant. Checking the common tag narrows the union, so a circle branch can use radius while a rectangle branch can use width and height.
type Shape = | { kind: "circle"; radius: number } | { kind: "square"; sideLength: number } | { kind: "rectangle"; width: number; height: number }; function unreachable(value: never): never { throw...