Advanced Typescript. Type Guards and Differentiating Types

Image for post
Image for post

Prerequisites

For our demo purposes, I’ll be using a simples TS project with two dev dependencies: typescript and ts-node (without any tsconfig file).

Image for post
Image for post

Type Guards and Differentiating Types

For TS types differentiation we can use three different mechanisms:

  • instanceof keyword;
  • user-defined Type Guards

1.1 Using “typeof” keyword

Image for post
Image for post

1.2 Using "instanceof" keyword

Image for post
Image for post

1.3 Using user-defined Type Guards

Type Guards are mostly used for complex type checking.

function isSomeType(var): var is SomeType {...}
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store