control flow analysis
TypeScript 2.0+
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.
let test: string | string[]; test = "this is a string"; test.toLowerCase(); // type 'string' test = ["these", "are", "strings"]; test.join(" "); // type 'string[]'
Above code is in same scope, but the type checker looks for the most specific type possible for the command
variable at any given location.
function testFunction(test: string | string[]): string { if (typeof test === "string") { // executes when test is type of string return test.toLowerCase(); } // else, assume it is an array return test.join(" "); }
Same idea, but with null
check:
type TOptions = { hasToBeString: string; nullableString?: string | null | undefined; }; function testNullable(test: TOptions): string { const { hasToBeString, nullableString } = person; if (!nullableString) { return hasToBeString; } }