TypeScript Blueprints by Ivo Gabe de Wolff

TypeScript Blueprints by Ivo Gabe de Wolff

Author:Ivo Gabe de Wolff [Wolff, Ivo Gabe de]
Language: eng
Format: azw3
Publisher: Packt Publishing
Published: 2016-07-28T04:00:00+00:00


Assignments

Previously, the compiler did not follow assignments of a variable. If a variable was reassigned in the block after an if statement, the narrowing would not be applied. Thus, in the next example, the type of x is string | number, both before and after the assignment:

let x: string | number = ...; if (typeof x === "string") { x = 4; }

With control flow based type analysis, these assignments can be checked. The type of x will be string before the assignment and number after it. Narrowing after an assignment works only for union types. The parts of the union type are filtered based on the assigned value. For types other than union types, the type of the variable will be reset to the initial type after an assignment.

This can be used to write a function that either accepts one value or a list of values, in one of the following ways:

function f(x: string | string[]) { if (typeof x === "string") x = [x]; // x: string[] } function g(x: string | string[]) { if (x instanceof Array) { for (const item of x) g(item); return; } // x: string }

With the same analysis, the compiler can also check for values that are possibly null or undefined. Instead of getting runtime errors saying undefined is not an object, you will get a compile time warning that a variable might be undefined or null.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.