Type guards

We can examine the type of an expression at runtime by using the typeof or instanceof operators. The TypeScript language service looks for these operators and will narrow down the inferred type accordingly when used in an if block:

let x: any = { /* ... */ };if(typeof x === 'string') {console.log(x.splice(3, 1)); // Error, 'splice' does not exist  on 'string'}// x is still anyx.foo(); // OK

In the preceding code snippet, we have declared a variable named x of type any. Later, we check the type of x at runtime by using the typeof operator. If the type of x results to be a string, we will try to invoke the method splice, which is supposed to be a member of the x variable. The TypeScript language service can understand the usage of ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.