TypeScript · Boundaries

TS0016Do not use instanceof for JavaScript built-ins from another realm

Report instanceof checks against JavaScript built-ins, such as Error, Date, Map, RegExp, Promise, Array and Object, on values that may come from another JavaScript realm.

Why it happens

Error, Date, Map, Set, RegExp, Promise, Array, Function and Object have one constructor per realm. A value created in a node:vm context, an iframe, or a Vitest vmThreads or vmForks pool fails instanceof against this realm's class, so the check takes the wrong branch. Values from the Vite module runner, a duplicated package, a worker or structuredClone() are built with this realm's built-ins, so most of these checks never see a foreign value, and the rule reports them at low confidence. It only reports values that crossed a boundary in this file: parameters typed unknown or any, results of calling a parameter, and module namespaces from import() or ssrLoadModule(). A parameter of a function that the file neither exports nor passes around is skipped when every call passes a value proven local, such as a literal or an object constructed with an unshadowed built-in. Catching an error does not establish its origin.

Fix

Use the realm-safe check: Array.isArray(value) for arrays, typeof value === 'function' for functions, Error.isError(value) or an Object.prototype.toString.call(value) brand check in a guard helper such as isError(value) or isDate(value) for the rest.

Example

Brand-check errors from a sandbox

Before

export function toSandboxError(error: unknown): Error {
  if (error instanceof Error) return error
  return new Error(String(error))
}

After

function isError(value: unknown): value is Error {
  return Object.prototype.toString.call(value) === '[object Error]'
}

export function toSandboxError(error: unknown): Error {
  if (isError(error)) return error
  return new Error(String(error))
}

Verify the fix

Run only this rule after editing so the report stays focused on the diagnostic you are closing:

pnpm vite-doctor . --extends auto,typescript/strict --rules typescript/boundaries/no-cross-realm-builtin-instanceof
Copyright © 2026