Codectionary / Developer documentation / TypeScript

Class Narrowing with instanceof

instanceof checks an object against a constructor’s runtime prototype relationship.

What it is and why to use it

instanceof checks an object against a constructor’s runtime prototype relationship. TypeScript uses it to narrow a union involving that class. It is useful when working with actual class instances that have different methods, rather than plain JSON descriptions.

Common mistakes and limitations

Interfaces have no runtime constructor and cannot be used with instanceof. Objects from another browser realm may have a different constructor identity. A Date instance can also be invalid, so checking instanceof alone does not guarantee toISOString will succeed.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

if (value instanceof Date) { /* Date methods */ }

Examples

Class Narrowing with instanceof

Standalone TypeScript 5.8+ example; expected output is explained below.

function day(value: Date | string): string {
  if (value instanceof Date) return value.toISOString().slice(0, 10);
  return value;
}
console.log(day(new Date("2024-06-01T12:00:00Z")));
console.log(day("Not scheduled"));
  1. The Date instance passes the runtime check and exposes toISOString.
  2. slice selects the ISO calendar-date portion of that UTC representation.
  3. The string alternative is returned unchanged. This avoids pretending a date string already has Date methods.
  4. Expected output: 2024-06-01 Not scheduled

Best practices

  • Interfaces have no runtime constructor and cannot be used with instanceof. Objects from another browser realm may have a different constructor identity. A Date instance can also be invalid, so checking instanceof alone does not guarantee toISOString will succeed.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading