Control flow based type analysis
TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.Previously, the type analysis performed for type guards was limited to if
statements and ?:
conditional expressions and didn’t include effects of assignments and control flow constructs such as return
and break
statements.With TypeScript 2.0, the type checker analyses all possible flows of control in statements and expressions to produce the most specific type possible (the narrowed type) at any given location for a local variable or parameter that is declared to have a union type.
Example
function foo(x: string | number | boolean) {
if (typeof x === "string") {
x; // type of x is string here
x = 1;
x; // type of x is number here
}
x; // type of x is number | boolean here
}
function bar(x: string | number) {
if (typeof x === "number") {
return;
}
x; // type of x is string here
}
Control flow based type analysis is particuarly relevant in —strictNullChecks
mode because nullable types are represented using union types:
function test(x: string | null) {
if (x === null) {
return;
}
x; // type of x is string in remainder of function
}
Furthermore, in —strictNullChecks
mode, control flow based type analysis includes definite assignment analysis for local variables of types that don’t permit the value undefined
.
function mumble(check: boolean) {
let x: number; // Type doesn't permit undefined
x; // Error, x is undefined
if (check) {
x = 1;
x; // Ok
}
x; // Error, x is possibly undefined
x = 2;
x; // Ok
}