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 any
x.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 typeof in a conditional statement. TypeScript will automatically assume that x must be a string and let us know that the splice method does not exist on the type string. This feature is known as type guards.