TypeScript · Narrowing and unions

instanceof guard

Narrows to a class at runtime. Catch values are unknown because anything can be thrown.

Syntax
if (error instanceof Error)

Example

Example
try {
  JSON.parse("{bad");
} catch (error) {
  if (error instanceof Error) console.log(error.message);
}

More in this group

Assertion function Discriminated union Exhaustive switch in operator Non-null assertion Type assertion Type predicate typeof guard

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course