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.

Official answer available

Preview the opening of the answer, then unlock the full walkthrough.

"To implement a discriminated union, we first need to define types that have a common, literal-typed property. This property is known as the discriminant or tag. Each type within the union will have a unique value for this property, which TypeScript can use to determine the correct type in a given context. Let's consider a practical example relevant to a Frontend Developer role, where we might be handling different shapes in a drawing application."

```typescript type Circle = { kind: 'circle'; radius: number; };...

Related Questions