TypeScript `Error` Subclassing in 2026: Why `instanceof` Still Lies in Transpiled Code and the Fix That Actually Works
Custom Error subclasses in TypeScript silently break instanceof checks when compiled to ES5. Learn exactly why the prototype chain snaps and the Object.setPrototypeOf fix that makes instanceof reliable again.
When TypeScript compiles a class that extends Error to an ES5 target, the generated constructor captures the return value of super() and returns it, leaving this pointing at a plain Error instance rather than your subclass. The result: instanceof YourError returns false even on objects your own constructor just produced. No compiler warning fires. The types look correct. The bug is entirely silent.

The fix is a one-liner placed immediately after the super() call: Object.setPrototypeOf(this, new.target.prototype). That single statement repairs the prototype chain before any method is ever called on the new instance, making every instanceof check on the inheritance ladder return the correct answer.

Key Takeaways
- TypeScript targets below
ES2015transpile class constructors in a way that breaks the prototype chain for any class extending a built-in likeError. Object.setPrototypeOf(this, new.target.prototype)placed aftersuper()is the canonical fix, documented directly in the TypeScript handbook.- Every level of a deep error hierarchy needs the fix independently. A fixed base class does not automatically protect subclasses.
- Cross-realm scenarios (iframes,
vm.runInNewContext) breakinstanceoffor a different structural reason thatsetPrototypeOfcannot solve. - Targeting
ES2015or above intsconfig.jsonavoids the transpilation problem entirely, but many production builds still cannot drop ES5 output.
The Root Cause: How TypeScript Transpiles ES6 Classes to ES5
The broken instanceof check is a direct consequence of how the ES5 __extends helper works when the base class is a native built-in.
In native ES2015, calling new Error() internally consults new.target to stamp the correct prototype onto the freshly allocated object. A subclass constructor calling super() hands new.target down the chain, so the runtime builds an instance whose prototype is already set to the subclass prototype. The whole thing works because the spec guarantees new.target propagates correctly through [[Construct]] calls.
ES5 has no [[Construct]] protocol and no new.target. When TypeScript emits __extends and replaces the super() call with something like _super.apply(this, arguments), the native Error constructor receives a plain function call rather than a new-triggered construction. Per the TypeScript 2.2 release notes, new.target has no meaningful value in that context, so Error allocates a fresh object and returns it. The TypeScript-generated wrapper then returns that fresh object, not the this your subclass was setting properties on. The subclass prototype never gets attached.

The TypeScript handbook notes this explicitly: when compiling to a target below ES2015, subclassing Error, Array, or similar built-ins may no longer work as expected because those constructors use new.target to adjust the prototype chain, and there is no way to ensure a value for new.target when invoking a constructor in ES5 (TypeScript Classes: Inheriting Built-in Types). The importHelpers tsconfig option (available since TypeScript 2.1) can pull __extends from tslib rather than inlining it, but that does not change the underlying behavior because the structural problem is in ES5's execution model, not in the helper's implementation (tsconfig: importHelpers).
Reproducing the Bug: Custom Error Classes That Silently Fail instanceof Checks
The following example uses a target of ES5 in tsconfig.json. Both the TypeScript types and the runtime output look plausible, but the instanceof check fails.
// tsconfig.json: { "compilerOptions": { "target": "ES5" } }
class DatabaseError extends Error {
constructor(
message: string,
public readonly code: number
) {
super(message);
this.name = "DatabaseError";
}
}
const err = new DatabaseError("Connection refused", 503);
console.log(err.message); // "Connection refused" — works
console.log(err instanceof DatabaseError); // false — silent bug
console.log(err instanceof Error); // false — also wrong
console.log(err.name); // "DatabaseError" — name property set, but prototype is wrongThe name property assignment succeeds because it runs on whatever object this is pointing at. The instanceof checks fail because Object.getPrototypeOf(err) returns Error.prototype, not DatabaseError.prototype. TypeScript's type system sees err as a DatabaseError throughout the file, so there is no squiggle, no compile-time hint, and no runtime warning until a catch block tries if (err instanceof DatabaseError) and silently falls through to the wrong branch.

This pattern surfaces most often in backend Node.js services that still target ES5 for bundler compatibility, or in libraries that ship a CommonJS build compiled from an older tsconfig. The error handling code looks structurally correct in every code review. The defect only appears under test or in production when a specific error type never matches.
The Fix: Object.setPrototypeOf and new.target.prototype
The correct repair is to call Object.setPrototypeOf immediately after super(), before any other property assignment in the constructor. The TypeScript 2.2 release notes document the exact pattern and the generated output (TypeScript 2.2: Support for new.target).
class DatabaseError extends Error {
constructor(
message: string,
public readonly code: number
) {
super(message);
// Repair the prototype chain before any property assignment.
Object.setPrototypeOf(this, new.target.prototype);
this.name = "DatabaseError";
}
}
const err = new DatabaseError("Connection refused", 503);
console.log(err instanceof DatabaseError); // true
console.log(err instanceof Error); // true
console.log(err.message); // "Connection refused"
console.log(err.name); // "DatabaseError"new.target refers to the constructor that was directly invoked with new. Because TypeScript 2.2 added support for new.target as a first-class construct (and emits a polyfill for ES5 targets), new.target.prototype resolves to the prototype of whatever the most-derived class is at construction time. That means a subclass of DatabaseError calling super() will also have its own prototype correctly installed, provided it also includes the setPrototypeOf call. Using new.target.prototype rather than DatabaseError.prototype hardcoded is the detail that matters for deeper hierarchies.
The handbook also notes that runtimes lacking Object.setPrototypeOf can fall back to setting __proto__ directly, though that escape hatch is not needed in any environment relevant in 2026.
Deep Error Hierarchies: Making instanceof Work Across Multiple Inheritance Levels
Every class in a hierarchy that extends a built-in needs its own setPrototypeOf call. A fixed parent class does not automatically protect its children.

// Level 1: application-wide base error
class AppError extends Error {
constructor(message: string, public readonly context?: Record<string, unknown>) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = this.constructor.name;
}
}
// Level 2: infrastructure domain
class DatabaseError extends AppError {
constructor(message: string, public readonly code: number) {
super(message, { code });
Object.setPrototypeOf(this, new.target.prototype);
}
}
// Level 3: specific failure type
class QueryTimeoutError extends DatabaseError {
constructor(query: string, timeoutMs: number) {
super(`Query timed out after ${timeoutMs}ms`, 408);
Object.setPrototypeOf(this, new.target.prototype);
this.context = { query, timeoutMs };
}
}
// Runtime verification
const err = new QueryTimeoutError("SELECT * FROM users", 5000);
console.log(err instanceof QueryTimeoutError); // true
console.log(err instanceof DatabaseError); // true
console.log(err instanceof AppError); // true
console.log(err instanceof Error); // true
console.log(err.name); // "QueryTimeoutError"The this.constructor.name assignment in AppError automatically picks up the subclass name because this.constructor reflects the actual runtime constructor, not the class where the assignment lives. That removes the need to repeat this.name = "QueryTimeoutError" in every leaf class.
One common mistake is placing Object.setPrototypeOf only in the topmost class and expecting it to cascade. It does not. Each super() call in the chain introduces a fresh opportunity for the prototype to be misassigned, so each constructor must repair its own link.
When the Fix Is Not Enough: Cross-Realm Errors and Error.isError()
Object.setPrototypeOf solves the transpilation problem but cannot fix cross-realm instanceof failures.
Each JavaScript realm (a browser window, an iframe, a vm.runInNewContext sandbox in Node.js) has its own copy of every built-in, including Error. An error thrown inside an iframe and caught in the parent frame has a prototype chain rooted in the iframe's Error.prototype, which is a different object from the parent's Error.prototype. As a result, err instanceof Error returns false even for a perfectly normal, non-subclassed error, and no amount of setPrototypeOf can help because the fix operates on the same realm's prototype objects.
| Scenario | instanceof reliable? | Recommended check |
|---|---|---|
| Same realm, ES5 target, no fix | No | Add setPrototypeOf |
| Same realm, ES5 target, with fix | Yes | instanceof works |
| Same realm, ES2015+ target | Yes | instanceof works natively |
| Cross-realm (iframe, vm sandbox) | No | Duck-type or Error.isError() |
| Serialized error (JSON over IPC) | No | Reconstruct or duck-type |

The TC39 proposal Error.isError() addresses the cross-realm case. Unlike instanceof, Error.isError() inspects an internal slot ([[ErrorData]]) that all Error objects carry regardless of which realm created them. At the time of writing, the proposal is at Stage 3 and is available in V8-based runtimes behind a flag. For production code today, the practical alternative is duck-typing: check for the presence of message and stack properties, or use a branded property your own error hierarchy stamps during construction.
TypeScript 4.4 introduced useUnknownInCatchVariables (enabled by default under strict), which types caught values as unknown rather than any. That change forces explicit narrowing before accessing .message or .stack, making the cross-realm problem visible at the type level even if it was invisible before (tsconfig: useUnknownInCatchVariables).
Structuring Domain Error Classes That Work Reliably in Any Target
A production-grade error hierarchy follows a consistent structure: one abstract base that handles the prototype fix and name assignment, and concrete subclasses that only add domain-specific fields.

// errors/base.ts
/**
* Abstract base for all application errors.
* Handles the prototype chain repair for ES5 targets and
* automatic name assignment from the runtime constructor.
*/
export abstract class AppError extends Error {
constructor(
message: string,
public readonly context: Record<string, unknown> = {}
) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = this.constructor.name;
}
/**
* Cross-realm safe check that works before Error.isError() is universally available.
*/
static isAppError(value: unknown): value is AppError {
return (
typeof value === "object" &&
value !== null &&
"__appError" in value &&
(value as AppError).__appError === true
);
}
// Brand property for cross-realm duck-typing.
readonly __appError = true as const;
}
// errors/http.ts
export class HttpError extends AppError {
constructor(
public readonly statusCode: number,
message: string,
context?: Record<string, unknown>
) {
super(message, context);
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class NotFoundError extends HttpError {
constructor(resource: string) {
super(404, `${resource} not found`, { resource });
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class UnauthorizedError extends HttpError {
constructor(reason: string) {
super(401, "Unauthorized", { reason });
Object.setPrototypeOf(this, new.target.prototype);
}
}// Usage in a request handler
import { AppError, HttpError, NotFoundError } from "./errors";
async function handleRequest(id: string): Promise<void> {
try {
const result = await fetchUser(id);
if (!result) throw new NotFoundError(`User/${id}`);
console.log(result);
} catch (err: unknown) {
// useUnknownInCatchVariables means err is unknown here.
if (err instanceof NotFoundError) {
console.error(`404: ${err.message}`, err.context);
} else if (err instanceof HttpError) {
console.error(`HTTP ${err.statusCode}: ${err.message}`);
} else if (AppError.isAppError(err)) {
// Cross-realm safe branch for any AppError descendant.
console.error(`App error: ${err.message}`);
} else {
throw err; // Re-throw unknowns.
}
}
}
Keeping the prototype fix in every constructor, even when it feels redundant, is the only approach that holds when a consumer subclasses NotFoundError in a downstream package compiled with a different target. The pattern also works cleanly alongside TypeScript utility types for building discriminated unions out of error hierarchies: see 10 TypeScript Utility Types for Bulletproof Code for how to compose these with conditional types. Teams exploring AI-assisted refactoring of large error hierarchies may find AI-Powered TypeScript Refactoring Workflows relevant for automating the migration of existing classes to this pattern.
Frequently Asked Questions
Does setting target to ES2015 or higher in tsconfig.json eliminate this problem?
Yes. When the TypeScript compiler targets ES2015 or above, it emits native class syntax and does not generate the __extends helper. The native class implementation preserves new.target through the constructor chain, so instanceof works without any Object.setPrototypeOf call. The fix is still harmless to include and is recommended for libraries that may be consumed in ES5 environments.
Why does err instanceof Error also return false, not just err instanceof MyError?
When the ES5 __extends helper causes the native Error constructor to return a new plain object, the value your constructor ultimately returns is that plain Error instance, not the this your subclass was building on. That plain object's prototype chain leads back to Error.prototype, but the object reference your variable holds is returned as-is, and the subclass wrapper never re-attaches its own prototype. So neither the subclass nor Error itself appears in the prototype chain of the variable you're checking.
Is Object.setPrototypeOf safe to call in constructors from a performance standpoint?
V8 and other modern engines optimize object shapes (hidden classes) aggressively. Calling Object.setPrototypeOf after an object is created can deoptimize that object's shape in the engine. For error objects specifically, the performance impact is negligible because errors are exceptional control-flow artifacts, not hot-path data structures. The fix is correct to use. If profiling ever surfaces it as a problem, targeting ES2015 output removes the need for it entirely.
Does this fix work when errors are serialized across a worker thread boundary?
No. Errors sent over postMessage or through Node.js worker message channels are structured-cloned, which strips the prototype chain entirely. The receiving side gets a plain object. Reconstruct the typed error on the receiving end using a factory function keyed on a name or type discriminant field included in the serialized payload.
What about the cause property added in ES2022?
The Error constructor has accepted a { cause } option since ES2022, and TypeScript's type definitions reflect this. Passing { cause: originalError } as the second argument to super() works correctly in combination with Object.setPrototypeOf. Node.js 16.9.0 added support for cause, and TypeScript's lib definitions include it under ES2022 and above. No additional fix is needed specifically for cause.
The Definitive Pattern for 2026: Error Subclassing You Can Actually Trust
The root issue has been documented since TypeScript 2.2, yet codebases keep shipping broken instanceof checks because the bug is invisible at the type layer and easy to miss in code review. The complete, durable answer has three parts: place Object.setPrototypeOf(this, new.target.prototype) immediately after every super() call in every class that participates in an Error hierarchy; assign this.name from this.constructor.name in the base class so leaf classes inherit the correct name automatically; and add a branded duck-type static guard for any code path where cross-realm errors may appear. Teams that can target ES2015 or higher across all their build artifacts eliminate the transpilation half of the problem outright and keep the setPrototypeOf calls only as a defensive measure for library consumers.
For contexts where large token windows and AI assistants are part of the development workflow, automated detection of missing setPrototypeOf calls in existing codebases is entirely tractable. See 2 Million Token Context Windows in Real Web Apps for how that kind of large-scale static analysis applies in practice.