Challenge - 5 Problems
Exhaustive Matcher Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of exhaustive match with union types
What is the output of this TypeScript code using exhaustive pattern matching with
match?Typescript
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function area(shape: Shape): number {
return match (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.size ** 2;
}
}
console.log(area({ kind: 'circle', radius: 3 }).toFixed(2));Attempts:
2 left
π‘ Hint
Think about the formula for the area of a circle and how the code calculates it.
β Incorrect
The code matches the shape kind 'circle' and calculates area as Ο * radiusΒ². For radius 3, area = Ο * 9 β 28.27.
β Predict Output
intermediateResult of exhaustive match with never type
What will this TypeScript code output when run?
Typescript
type Status = 'success' | 'error'; function handleStatus(status: Status) { return match (status) { case 'success': return 'Yay!'; case 'error': return 'Oops!'; } } console.log(handleStatus('error'));
Attempts:
2 left
π‘ Hint
Check which case matches the input 'error'.
β Incorrect
The input 'error' matches the second case, so the function returns 'Oops!'.
π§ Debug
advancedIdentify the error in exhaustive match
What error does this TypeScript code produce?
Typescript
type Command = { type: 'start' } | { type: 'stop' } | { type: 'pause' };
function execute(cmd: Command) {
return match (cmd.type) {
case 'start':
return 'Started';
case 'stop':
return 'Stopped';
}
}
execute({ type: 'pause' });Attempts:
2 left
π‘ Hint
Check if all union cases are handled in the match.
β Incorrect
The match does not handle the 'pause' case, so TypeScript reports a compile error for non-exhaustive matching.
π Syntax
advancedWhich option causes a syntax error in exhaustive match?
Which of the following TypeScript code snippets causes a syntax error due to incorrect exhaustive pattern matching syntax?
Attempts:
2 left
π‘ Hint
Look for missing punctuation or keywords in the match cases.
β Incorrect
Option A is missing a semicolon or return keyword between cases, causing a syntax error.
π Application
expertNumber of cases needed for exhaustive match
Given this TypeScript union type, how many cases must a
match statement cover to be exhaustive?Typescript
type Event =
| { type: 'click'; x: number; y: number }
| { type: 'keydown'; key: string }
| { type: 'resize'; width: number; height: number }
| { type: 'scroll'; scrollTop: number };
// How many cases are needed in match(event.type) to be exhaustive?Attempts:
2 left
π‘ Hint
Count the distinct union members by their 'type' property.
β Incorrect
There are 4 distinct 'type' values in the union, so 4 cases are needed for exhaustive matching.
