Sub topic 7
Narrowing with instanceof
This chapter assumes you know the typeof, equality, and in checks from the earlier chapters. It also assumes you are comfortable with TypeScript classes and extends, and that you know what a union type is.
What instanceof checks
At runtime, value instanceof Constructor is true when Constructor.prototype appears somewhere in the prototype chain of value. TypeScript uses that check as a type guard:
- In the true branch, the value is narrowed to the instance type of the constructor.
- In the false branch, the compiler removes every union member that is assignable to that instance type.
The simplest case is a union of an Error and a string:
function messageOf(error: Error | string): string {
return error instanceof Error ? error.message : error;
}In the true branch, error is Error, so .message is allowed. In the false branch, Error has been removed, so error is string.
Narrowing unknown values in catch blocks
The most common use of instanceof is in catch clauses. With strict enabled, the useUnknownInCatchVariables option makes the caught value unknown, because JavaScript lets you throw anything. You must narrow it before reading properties:
function run(action: () => void): string {
try {
action();
return "ok";
} catch (error) {
if (error instanceof Error) {
return error.message;
}
return `Non-error thrown: ${String(error)}`;
}
}The check works on unknown as well as on unions. When the left side is unknown, a true result narrows it to the class instance type. The false branch stays unknown, because the compiler has no union members to remove.
Narrowing among your own classes
You can define a family of error classes and tell them apart with instanceof:
class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.name = "HttpError";
this.status = status;
}
}
class TimeoutError extends Error {
seconds: number;
constructor(seconds: number) {
super(`Timed out after ${seconds}s`);
this.name = "TimeoutError";
this.seconds = seconds;
}
}
function describe(error: unknown): string {
if (error instanceof HttpError) {
return `HTTP ${error.status}: ${error.message}`;
}
if (error instanceof TimeoutError) {
return `Retry in ${error.seconds * 2}s`;
}
if (error instanceof Error) {
return error.message;
}
return String(error);
}Check the most specific class first
Because HttpError extends Error, every HttpError also passes error instanceof Error. If the generic Error check came first, it would catch every subclass and the specific branches would never run. At runtime, the first matching branch wins. Order your checks from the most derived class to the base class.
Built-in classes
instanceof also works with built-in constructors. These are common cases:
| Check | Narrows to | Notes |
|---|---|---|
| `value instanceof Date` | `Date` | Useful for inputs that accept a date or an ISO string. |
| `value instanceof Map` | `Map<any, any>` | Generic arguments are not recoverable from the check. |
| `value instanceof RegExp` | `RegExp` | Good for accepting a pattern or a plain string. |
| `value instanceof Promise` | `Promise<any>` | Often used for "value or promise of value" parameters. |
| `value instanceof Error` | `Error` | Works for subclasses such as `TypeError`. |
Here is a function that accepts either a Date or a string:
function toDate(input: string | Date): Date {
if (input instanceof Date) {
return input;
}
return new Date(input);
}For arrays, prefer Array.isArray(value). It is a built-in type guard, and it also works across realms (a realm is a separate JavaScript global environment, such as an iframe).
Cases where instanceof cannot help
Interfaces and type aliases have no runtime value
instanceof needs a constructor function at runtime. Interfaces and type aliases are erased during compilation, so they cannot appear on the right-hand side:
interface Fish {
swim(): void;
}
// Error: 'Fish' only refers to a type, but is being used as a value here.
// if (animal instanceof Fish) { ... }For plain object shapes, use the in operator, a discriminant property, or a user-defined type guard.
Primitives are never instances
"hello" instanceof String is false, because a primitive string is not an object. Use typeof for string, number, boolean, bigint, and symbol. The instanceof check applies only to objects.
Parsed JSON has no class instances
JSON.parse returns plain objects and arrays. Even if the data looks exactly like a User class, parsed instanceof User is false. Validate such data with a type predicate, which a later chapter covers.
Objects from another realm or another copy of a package
Each realm has its own Error, Array, and Date. An error created in an iframe or a vm context fails instanceof Error in your main realm. The same happens when two copies of a package are installed at different versions: a class from copy A does not match the class from copy B. In those situations, the compile-time narrowing is correct for the types, but the runtime check disagrees. Use a duck-typed check (a check on the object's shape) or a discriminant property instead.
Custom Symbol.hasInstance
A class can override instanceof behavior with a static [Symbol.hasInstance] method. TypeScript still narrows as if the standard check applied. This is rare, but it means the compiler trusts the class to behave honestly.
The structural typing gotcha
TypeScript compares types by their shape, not by their name. Narrowing by instanceof follows the same rule. The false branch removes every union member that is assignable to the class type, and a plain object type with the same shape counts:
class Point {
x = 0;
y = 0;
}
type Coord = { x: number; y: number };
function check(value: Point | Coord): string {
if (value instanceof Point) {
return "point";
}
// Coord is assignable to Point, so nothing is left in this branch.
const leftover: never = value;
return leftover;
}The compiler treats Coord as if it were a Point, so the false branch becomes never. At runtime, a plain { x: 1, y: 2 } object is not a Point instance, so the code would reach that branch with a real value.
Combining instanceof with other guards
You can combine checks in a single condition. Each part narrows the value for the parts after it:
function statusOf(error: unknown): number {
if (error instanceof HttpError && error.status >= 500) {
return 502;
}
if (error instanceof HttpError) {
return error.status;
}
return 500;
}In the first condition, error.status is legal only because the left side of && already narrowed error to HttpError.
You can also wrap an instanceof check inside a user-defined type guard when you reuse it often:
function isHttpError(value: unknown): value is HttpError {
return value instanceof HttpError;
}This is useful with Array.prototype.filter, which does not infer type predicates from a bare instanceof check in older compiler versions. The explicit predicate works everywhere:
const items: Array<HttpError | string> = [new HttpError(404, "Not found"), "note"];
const httpErrors: HttpError[] = items.filter(isHttpError);Common mistakes
- Putting a base-class check before a subclass check, so the subclass branch is dead code.
- Using
instanceofon a type or interface name, which fails to compile. - Trusting
instanceoffor data fromJSON.parse, a network layer, orstructuredClone, none of which preserve class identity in the way you expect. - Forgetting that
catch (error)isunknownunderstrict, and readingerror.messagewithout a check. - Assuming a thrown value is always an
Error. Code canthrow "text"orthrow { code: 1 }, so keep a fallback branch.
Exercise
A function receives value: unknown from a catch block. You want to return value.message when it is a TypeError, value.message for any other Error, and "unknown" otherwise. Which order must the two instanceof checks use, and why?
Show answer
Check value instanceof TypeError first, then value instanceof Error. TypeError extends Error, so a TypeError also passes the Error check. If Error came first, it would catch every TypeError and the more specific branch would never run. Both branches can return value.message, but the order matters as soon as the TypeError branch does anything different.
Exercise
Why does if (animal instanceof Fish) fail to compile when Fish is declared with interface Fish { swim(): void }, and what can you use instead?
Show answer
An interface exists only at compile time and has no runtime value, but instanceof needs a constructor function to inspect the prototype chain. Use the in operator ("swim" in animal), a discriminant property, or a user-defined type guard with a value is Fish predicate. You could also declare Fish as a class if you create real instances.