Control flow analysis errors
TypeScript 1.8 introduces control flow analysis to help catch common errors that users tend to run into.Read on to get more details, and check out these errors in action:
Unreachable code
Statements guaranteed to not be executed at run time are now correctly flagged as unreachable code errors. For instance, statements following unconditional return
, throw
, break
or continue
statements are considered unreachable. Use —allowUnreachableCode
to disable unreachable code detection and reporting.
Example
Here’s a simple example of an unreachable code error:
function f(x) {
if (x) {
return true;
}
else {
return false;
}
x = 0; // Error: Unreachable code detected.
}
A more common error that this feature catches is adding a newline after a return
statement:
function f() {
return // Automatic Semicolon Insertion triggered at newline
{
x: "string" // Error: Unreachable code detected.
}
}
Since JavaScript automatically terminates the return
statement at the end of the line, the object literal becomes a block.
Unused labels
Unused labels are also flagged. Just like unreachable code checks, these are turned on by default; use —allowUnusedLabels
to stop reporting these errors.
Example
loop: while (x > 0) { // Error: Unused label.
x++;
}
Implicit returns
Functions with code paths that do not return a value in JS implicitly return undefined
. These can now be flagged by the compiler as implicit returns. The check is turned off by default; use —noImplicitReturns
to turn it on.
Example
function f(x) { // Error: Not all code paths return a value.
if (x) {
return false;
}
// implicitly returns `undefined`
}
Case clause fall-throughs
TypeScript can reports errors for fall-through cases in switch statement where the case clause is non-empty.This check is turned off by default, and can be enabled using —noFallthroughCasesInSwitch
.
Example
With —noFallthroughCasesInSwitch
, this example will trigger an error:
switch (x % 2) {
case 0: // Error: Fallthrough case in switch.
console.log("even");
case 1:
console.log("odd");
break;
}
However, in the following example, no error will be reported because the fall-through case is empty:
switch (x % 3) {
case 0:
case 1:
console.log("Acceptable");
break;
case 2:
console.log("This is *two much*!");
break;
}