TypeScript User-defined Type Guards


  • typeof x === "type name"
  • x instanceof TypeName
  • function(foo: any): foo is TypeName { /* code returning boolean */ }


Using type annotations in TypeScript constrains the possible types your code will need to deal with, but it is still common to need to take different code paths based on the runtime type of a variable.

Type guards let you write code that discriminates based on the runtime type of a variable, while remaining strongly typed and avoiding casts (also known as type assertions).