0
0
Typescriptprogramming~5 mins

Discriminated unions in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ADiscriminant
BIdentifier
CSelector
DMarker
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?
Apet has both bark and meow methods
Bpet has a meow method
Cpet has a bark method
Dpet has no methods
Which TypeScript feature helps ensure all cases of a discriminated union are handled?
Aany type
Bvoid type
Cunknown type
Dnever type
What happens if you use a discriminated union without a common literal property?
ATypeScript can still narrow types perfectly
BTypeScript cannot narrow types automatically
CIt causes a runtime error
DIt converts the union to any
Which of these is a valid discriminant property value for a discriminated union?
Astring literal
Bboolean
Cnumber
Dobject
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.