instanceof

Narrows the type to a class by checking whether the object was created by it.

On this page

Example

#
TypeScript
class ValidationError extends Error {
  constructor(public field: string, message: string) {
    super(message)
    this.name = 'ValidationError'
  }
}

function describeError(error: unknown): string {
  if (error instanceof ValidationError) return `Field ${error.field}: ${error.message}`
  if (error instanceof Error) return `Error: ${error.message}`
  return 'Unknown error'
}

console.log(describeError(new ValidationError('email', 'invalid address')))
console.log(describeError(new Error('no connection')))
console.log(describeError('oops'))
Result
Field email: invalid address
Error: no connection
Unknown error

Definition and usage

#

The instanceof operator checks at runtime whether an object comes from a given class (has it in its prototype chain). TypeScript uses this check to narrow the type inside the if block.

It’s most useful with errors (error instanceof Error), dates (value instanceof Date), and your own classes, for example different kinds of exceptions.

It only works with classes and constructors that exist after compilation. You can’t use instanceof with an interface, because interfaces disappear in JavaScript.

Syntax

#
Syntax
if (value instanceof Class) {
  // value: Class
}

Good practices

#
  • In a catch block the error has the type unknown. Check error instanceof Error before you read message.
  • To check the shape of plain objects (e.g. from JSON), instanceof won’t work. Use the in operator or a type guard.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.