What is exhaustive pattern matching in TypeScript?
Exhaustive pattern matching means checking all possible cases of a value so that no case is missed. It helps catch errors when new cases are added.
Click to reveal answer
intermediate
How can you enforce exhaustive checks in TypeScript's switch statements?
You can add a default case that throws an error or uses the never type to make sure all cases are handled.
Click to reveal answer
intermediate
What is the never type used for in exhaustive pattern matching?
The never type represents values that should never happen. Using it in a default case helps TypeScript warn if some cases are missing.
Click to reveal answer
beginner
Why is exhaustive pattern matching helpful in real-life programming?
It prevents bugs by making sure you handle every possible case, especially when your data types change or grow over time.
Click to reveal answer
intermediate
Show a simple example of exhaustive pattern matching with a switch on a union type in TypeScript.
```typescript
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function area(shape: Shape) {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.size ** 2;
default:
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
```
Click to reveal answer
What does the never type represent in TypeScript?
AA number value
BA string value
CA value that never occurs
DAny possible value
✗ Incorrect
The never type means a value that should never happen, useful for exhaustive checks.
Why add a default case with a never type in a switch?
ATo catch missing cases and get TypeScript errors
BTo ignore all cases
CTo return a default value
DTo make the code shorter
✗ Incorrect
Adding a default with never helps TypeScript warn if some cases are not handled.
What happens if you forget a case in exhaustive pattern matching?
AThe program always crashes
BThe missing case is handled automatically
CNothing happens, code runs fine
DTypeScript can warn you if set up correctly
✗ Incorrect
If you use exhaustive checks, TypeScript warns you about missing cases to avoid bugs.
Which TypeScript feature helps you create union types for pattern matching?
AUnion types using |
BClasses
CInterfaces only
DEnums only
✗ Incorrect
Union types with | let you combine types for pattern matching.
What is the main benefit of exhaustive pattern matching?
AAvoid using switch statements
BCatch all possible cases and avoid bugs
CReduce code size
DMake code run faster
✗ Incorrect
Exhaustive matching ensures all cases are handled, preventing bugs.
Explain how to implement exhaustive pattern matching in TypeScript using a switch statement.
Think about how to make TypeScript check all cases.
You got /4 concepts.
Why is exhaustive pattern matching important when your data types change over time?
Consider what happens if you add a new case but forget to handle it.
You got /3 concepts.
Practice
(1/5)
1.
What is the main purpose of exhaustive pattern matching in TypeScript?
easy
A. To allow dynamic typing in TypeScript
B. To ensure all possible cases of a union type are handled
C. To improve runtime performance by skipping cases
D. To automatically generate switch cases
Solution
Step 1: Understand union types and pattern matching
Exhaustive pattern matching ensures every variant of a union type is explicitly handled in code.
Step 2: Identify the purpose of exhaustive checks
This prevents missing cases that could cause bugs or unexpected behavior.
Final Answer:
To ensure all possible cases of a union type are handled -> Option B
Quick Check:
Exhaustive pattern matching = handle all cases [OK]
Hint: Exhaustive means covering every case without missing any [OK]
Common Mistakes:
Thinking it improves runtime speed
Confusing with dynamic typing
Assuming it auto-generates code
2.
Which of the following switch statements correctly uses exhaustive pattern matching for this union type?
type Shape = 'circle' | 'square' | 'triangle';
easy
A. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; }
B. switch(shape) { case 'circle': break; case 'square': break; default: break; }
C. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: const _exhaustiveCheck: never = shape; }
D. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: console.log('unknown'); }
Solution
Step 1: Check all cases are handled
Cases for 'circle', 'square', and 'triangle' are present in options B, C, and D.
Step 2: Verify exhaustive check with never type
Only switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: const _exhaustiveCheck: never = shape; } uses default with const _exhaustiveCheck: never = shape; to enforce exhaustiveness.
Final Answer:
switch with all cases and default assigning to never -> Option C
Quick Check:
Exhaustive switch = all cases + never default [OK]
Hint: Look for default assigning to never for exhaustiveness [OK]
Common Mistakes:
Omitting the default case with never assignment
Using default without never type
Missing one of the union cases
3.
What will be the output of this TypeScript code?
type Status = 'success' | 'error';
function handleStatus(status: Status) {
switch (status) {
case 'success':
return 'Yay!';
case 'error':
return 'Oops!';
default:
const _exhaustiveCheck: never = status;
return _exhaustiveCheck;
}
}
console.log(handleStatus('success'));
medium
A. Compilation error
B. "Oops!"
C. Runtime error
D. "Yay!"
Solution
Step 1: Analyze the switch cases for 'success'
The input is 'success', so the first case matches and returns 'Yay!'.
Step 2: Check the default case usage
The default case is unreachable here but ensures exhaustiveness by assigning to never.
Final Answer:
"Yay!" -> Option D
Quick Check:
Input 'success' returns 'Yay!' [OK]
Hint: Match input case to return value directly [OK]
Common Mistakes:
Thinking default case runs for valid inputs
Expecting runtime or compile errors
Confusing return values for cases
4.
Identify the error in this exhaustive pattern matching code:
type Direction = 'up' | 'down' | 'left' | 'right';
function move(dir: Direction) {
switch (dir) {
case 'up':
return 'Moving up';
case 'down':
return 'Moving down';
case 'left':
return 'Moving left';
default:
const _exhaustiveCheck: never = dir;
return _exhaustiveCheck;
}
}
medium
A. Missing case for 'right' in the switch statement
B. Default case should not assign to never
C. Function should return void instead of string
D. Switch statement syntax is incorrect
Solution
Step 1: Check all union cases in switch
Cases for 'up', 'down', and 'left' exist, but 'right' is missing.
Step 2: Understand the role of default with never
The default assigns to never to catch unhandled cases, so missing 'right' causes a compile error.
Final Answer:
Missing case for 'right' in the switch statement -> Option A
Quick Check:
All union cases must be handled explicitly [OK]
Hint: Check if all union members have cases before default [OK]
Common Mistakes:
Assuming default covers missing cases silently
Misusing never assignment in default
Ignoring missing union members
5.
Given this nested union type, which switch structure correctly uses exhaustive pattern matching to handle all cases?
A. switch(animal.type) {
case 'dog':
switch(animal.breed) {
case 'bulldog': break;
case 'beagle': break;
default: const _exhaustiveCheck: never = animal.breed;
}
break;
case 'cat':
switch(animal.color) {
case 'black': break;
case 'white': break;
default: const _exhaustiveCheck: never = animal.color;
}
break;
default: const _exhaustiveCheck: never = animal.type;
}
B. switch(animal.type) {
case 'dog':
if(animal.breed === 'bulldog' || animal.breed === 'beagle') break;
break;
case 'cat':
if(animal.color === 'black' || animal.color === 'white') break;
break;
default: const _exhaustiveCheck: never = animal.type;
}
C. switch(animal.type) {
case 'dog':
case 'cat':
break;
default: const _exhaustiveCheck: never = animal.type;
}
D. switch(animal.type) {
case 'dog':
switch(animal.breed) {
case 'bulldog': break;
default: const _exhaustiveCheck: never = animal.breed;
}
break;
case 'cat':
switch(animal.color) {
case 'black': break;
case 'white': break;
}
break;
default: const _exhaustiveCheck: never = animal.type;
}
Solution
Step 1: Check outer switch covers all 'type' cases
Cases for 'dog' and 'cat' are present with default assigning to never.
Step 2: Check inner switches cover all nested union cases
For 'dog', both 'bulldog' and 'beagle' are handled with default never; for 'cat', both 'black' and 'white' are handled similarly.
Step 3: Verify no missing cases in nested switches
All nested union members are covered with exhaustive checks.
Final Answer:
Nested switches with all cases and never defaults for both levels -> Option A
Quick Check:
Nested exhaustive switches = all cases + never defaults [OK]
Hint: Use nested switches with never defaults for each union level [OK]
Common Mistakes:
Skipping some nested union cases
Using if conditions without exhaustive checks
Missing never assignment in inner switches
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.