Recall & Review
beginner
What is a discriminated union in TypeScript?
A discriminated union is a special kind of union type that uses a common literal property (called the discriminant) to tell which type in the union is being used. This helps TypeScript safely narrow down the type.
Click to reveal answer
beginner
Why do discriminated unions use a common literal property?
The common literal property acts like a tag or label that tells TypeScript which shape or variant of the union is active. This makes it easy to check the property and get correct type information.
Click to reveal answer
beginner
Example: What does this code do?<br>
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };This defines a discriminated union called Shape. It can be either a circle with a radius or a square with a size. The 'kind' property tells which shape it is.
Click to reveal answer
intermediate
How does TypeScript narrow types with discriminated unions in a switch statement?
When you switch on the discriminant property (like 'kind'), TypeScript knows which type you are working with in each case block, so it allows only the properties of that specific type.
Click to reveal answer
intermediate
What happens if you forget to handle a case in a discriminated union switch?
TypeScript can warn you if you use the 'never' type in a default case to catch unhandled cases. This helps you write safer code by ensuring all variants are handled.
Click to reveal answer
What is the key property called that discriminated unions use to identify the type?
✗ Incorrect
The key property is called the discriminant. It is a literal property used to distinguish types in the union.
Given this type:<br>
type Pet = { type: 'dog'; bark: () => void } | { type: 'cat'; meow: () => void };<br>What will TypeScript know inside if(pet.type === 'dog') block?✗ Incorrect
Inside the if block, TypeScript knows pet is the dog type, so it has a bark method.
Which TypeScript feature helps ensure all cases of a discriminated union are handled?
✗ Incorrect
The never type is used to catch unhandled cases in discriminated unions, helping with exhaustiveness checking.
What happens if you use a discriminated union without a common literal property?
✗ Incorrect
Without a common literal property, TypeScript cannot automatically narrow the union types.
Which of these is a valid discriminant property value for a discriminated union?
✗ Incorrect
The discriminant property must be a literal type, usually a string literal, to distinguish union members.
Explain what a discriminated union is and how it helps with type safety in TypeScript.
Think about how a special property helps TypeScript know exactly which type you are working with.
You got /4 concepts.
Describe how you would use a switch statement with a discriminated union to handle different cases.
Imagine you have a shape type with different kinds and want to do something different for each kind.
You got /4 concepts.