TS7029
Fallthrough case in switch.
Broken Code ❌
export function f(x: unknown) {
switch (true) {
case typeof x === 'string':
// 'x' is a 'string' here
console.log(x.toUpperCase());
// falls through...
case Array.isArray(x):
// 'x' is a 'string | any[]' here.
console.log(x.length);
// falls through...
default:
// 'x' is 'unknown' here.
// ...
}
}Solution:
To address the fallthrough warning in a TypeScript switch statement, you can explicitly use the break statement.
Fixed Code ✔️
export function f(x: unknown) {
switch (true) {
case typeof x === 'string':
// 'x' is a 'string' here
console.log(x.toUpperCase());
break; // Properly terminate the case
case Array.isArray(x):
// 'x' is a 'string | any[]' here.
console.log(x.length);
break; // Properly terminate the case
default:
// 'x' is 'unknown' here.
// Additional logic can be added here
break; // Properly terminate the default case
}
}