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:

  1. var x: any = /* ... */;
  2. if(typeof x === 'string') {
  3. console.log(x.subtr(1)); // Error, 'subtr' does not exist on 'string'
  4. }
  5. // x is still any here
  6. x.unknown(); // OK

Using typeof with union types and else:

  1. var x: string | HTMLElement = /* ... */;
  2. if(typeof x === 'string') {
  3. // x is string here, as shown above
  4. }
  5. else {
  6. // x is HTMLElement here
  7. console.log(x.innerHTML);
  8. }

Using instanceof with classes and union types:

  1. class Dog { woof() { } }
  2. class Cat { meow() { } }
  3. var pet: Dog|Cat = /* ... */;
  4. if (pet instanceof Dog) {
  5. pet.woof(); // OK
  6. }
  7. else {
  8. pet.woof(); // Error
  9. }