Typescript: Type Guards

September 12th, 2022

type information is only available at compile time, not at runtime

 

Type guards are ways to check at runtime if an object matches.

use of keywords

  • typeof

  • instanceof

  • in

 

instanceof

if(x instanceof SomeObjectConstructor)

 

typeof

if(typeof a === 'string')

typeof only works with

"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

 

in

if('firstName' in obj)

checks if attribute exists

 

(src: TypeScript Type GuardsAWS & Typescript Masterclass - Typescript recap)