TypeScriptUser-defined Type Guards


Syntax

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

Remarks

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