TypeScriptUnions and narrowing
instanceof
Narrows the type to a class by checking whether the object was created by it.
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
catchblock the error has the typeunknown. Checkerror instanceof Errorbefore you readmessage. - To check the shape of plain objects (e.g. from JSON),
instanceofwon’t work. Use theinoperator or a type guard.
Related entries
#- Type narrowingDetermining a more precise type for a value based on checks in your code.
- Type guards (value is T)Custom checking functions that narrow the type at the call site.
- The in operatorNarrows a union of objects by checking whether an object has a given property.
- unknownThe safe counterpart to any: a value of an unknown type that you must check before use.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.