The requirement for a final default
clause is defensive programming. The clause should either take appropriate action, or contain a
suitable comment as to why no action is taken.
Noncompliant code example
switch (param) { //missing default clause
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}
switch (param) {
default: // default clause should be the last one
error();
break;
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}
Compliant solution
switch (param) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
default:
error();
break;
}
Exceptions
The rule ignores switch
statements where the discriminant is a TypeScript union and there is a case
branch for each
constituent.
type Season = 'Spring' | 'Summer' | 'Fall' | 'Winter';
let season: Season;
switch (season) {
case 'Spring':
wakeUp();
break;
case 'Summer':
getOut();
break;
case 'Fall':
saveFood();
break;
case 'Winter':
sleep();
break;
}
The same applies for TypeScript enums.
enum Direction {
Up,
Down
}
let dir: Direction;
switch (dir) {
case Direction.Up:
getUp();
break;
case Direction.Down:
getDown();
break;
}