0Pricing
TypeScript Academy · Lesson

instanceof and in Narrowing

Narrow class instances and object shapes.

Welcome

`instanceof` narrows class instances and `in` narrows object types based on property presence. Both are essential for working with complex unions.

instanceof Narrowing

Use `instanceof` to check if a value is an instance of a class. TypeScript narrows the type to that class.
function handle(err: Error | string) {
  if (err instanceof Error) {
    console.log(err.message); // err: Error
  } else {
    console.log(err); // err: string
  }
}

All lessons in this course

  1. typeof and Truthiness Narrowing
  2. instanceof and in Narrowing
  3. User-Defined Type Guard Functions
  4. Exhaustiveness Checking with never
← Back to TypeScript Academy