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 ...