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:

cfa

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:

  1. function f(x) {
  2. if (x) {
  3. return true;
  4. }
  5. else {
  6. return false;
  7. }
  8. x = 0; // Error: Unreachable code detected.
  9. }

A more common error that this feature catches is adding a newline after a return statement:

  1. function f() {
  2. return // Automatic Semicolon Insertion triggered at newline
  3. {
  4. x: "string" // Error: Unreachable code detected.
  5. }
  6. }

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
  1. loop: while (x > 0) { // Error: Unused label.
  2. x++;
  3. }

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
  1. function f(x) { // Error: Not all code paths return a value.
  2. if (x) {
  3. return false;
  4. }
  5. // implicitly returns `undefined`
  6. }

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:

  1. switch (x % 2) {
  2. case 0: // Error: Fallthrough case in switch.
  3. console.log("even");
  4. case 1:
  5. console.log("odd");
  6. break;
  7. }

However, in the following example, no error will be reported because the fall-through case is empty:

  1. switch (x % 3) {
  2. case 0:
  3. case 1:
  4. console.log("Acceptable");
  5. break;
  6. case 2:
  7. console.log("This is *two much*!");
  8. break;
  9. }