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 narrow down the type safely.
Click to reveal answer
beginner
How does TypeScript use the discriminant property to narrow types?
TypeScript checks the value of the discriminant property in a conditional statement. Based on its value, it knows exactly which type from the union is active and narrows the type accordingly.
Click to reveal answer
beginner
Example: Given a union type with a 'kind' property, how do you narrow it?
Use a switch or if statement on the 'kind' property. For example:<br>
switch (shape.kind) {<br> case 'circle':<br> // shape is Circle here<br> break;<br> case 'square':<br> // shape is Square here<br> break;<br>}Click to reveal answer
intermediate
Why is discriminated union narrowing safer than using type assertions?
Because TypeScript automatically checks the discriminant property and narrows the type, it prevents mistakes that can happen if you manually tell TypeScript a type without checking. This reduces bugs.
Click to reveal answer
intermediate
What happens if you forget to handle one case in a discriminated union switch?
TypeScript can warn you if you enable strict checks. Missing a case means your code might not handle all possible types, which can cause runtime errors.
Click to reveal answer
What property is essential for discriminated union narrowing in TypeScript?
✗ Incorrect
Discriminated unions rely on a common literal property (discriminant) to distinguish types.
How does TypeScript narrow a discriminated union inside a switch statement?
✗ Incorrect
TypeScript uses the discriminant property's value in each case to narrow the type.
Which of these is a benefit of discriminated union narrowing?
✗ Incorrect
Discriminated unions provide automatic type safety by narrowing types based on a property.
What keyword is commonly used to check the discriminant property in TypeScript?
✗ Incorrect
The switch statement is commonly used to check the discriminant property for narrowing.
If a discriminated union has a 'type' property with values 'A' or 'B', what happens if you check 'type === "A"'?
✗ Incorrect
Checking the discriminant property value narrows the variable to the matching type.
Explain how discriminated union narrowing works in TypeScript and why it is useful.
Think about how a shared property helps TypeScript know the exact type.
You got /5 concepts.
Describe a simple example of a discriminated union and how you would use a switch statement to narrow its type.
Use shapes like circle and square with a 'kind' property.
You got /4 concepts.