Type Guards
A common pattern in JavaScript is to use typeof
or instanceof
to examine the type of an expression at runtime. TypeScript now understands these conditions and will change type inference accordingly when used in an if
block.
Using typeof
to test a variable:
var x: any = /* ... */;
if(typeof x === 'string') {
console.log(x.subtr(1)); // Error, 'subtr' does not exist on 'string'
}
// x is still any here
x.unknown(); // OK
Using typeof
with union types and else
:
var x: string | HTMLElement = /* ... */;
if(typeof x === 'string') {
// x is string here, as shown above
}
else {
// x is HTMLElement here
console.log(x.innerHTML);
}
Using instanceof
with classes and union types:
class Dog { woof() { } }
class Cat { meow() { } }
var pet: Dog|Cat = /* ... */;
if (pet instanceof Dog) {
pet.woof(); // OK
}
else {
pet.woof(); // Error
}