instanceof instanceof Narrowing
Last updated: 2026-10-22
instanceof instanceof Narrowing
The instanceof guard works on unions of classes: it checks whether a value is an instance of a class, and TypeScript narrows the type to that class. It performs a real prototype-chain check at runtime and is the standard tool for unions involving Date, Map, Error or your own classes.
| Group | Narrowing & Assertions |
|---|---|
| Kind | Operator |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
function logValue(x: Date | string) {
if (x instanceof Date) {
console.log(x.toISOString()); // x: Date
} else {
console.log(x.toUpperCase()); // x: string
}
}
⚙️ Parameters
| instanceof Klass | At runtime, walks the prototype chain to see whether Klass.prototype appears on the object; TS simultaneously narrows the type to Klass (or a subclass) |
|---|
Returns:The instanceof expression returns a boolean; narrowing happens at compile time, and the right-hand side must be a constructor function with a prototype.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
Article: TS Basics
Video: 95s
(Runtime output after transpilation; item.title and item.duration type-check because instanceof narrowing is in effect — narrowing is guaranteed statically by tsc, at runtime there are only values)
💡 Notes
ℹ️ Info instanceof is a genuine runtime check (prototype chain), so it does not recognize "duck-typed" objects produced by JSON.parse — their prototype is Object.prototype, not your class.
⚠️ Note instanceof cannot be used with interfaces — they are erased at compile time and there is no constructor to test. Distinguish interface shapes with in, custom guards or discriminated unions.
💡 Tip Objects from another iframe or vm realm have a different prototype than the local class, so instanceof can wrongly return false. Validate such boundary data structurally with a custom type guard.
🏷️ Related Narrowing & Assertions
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Does instanceof work with subclass narrowing?
A Yes. instanceof walks the prototype chain, so a subclass instance passes instanceof Parent too, while a parent instance fails instanceof Child. TS accounts for inheritance when narrowing.
Q Why does instanceof always return false for JSON.parse results?
A JSON.parse produces plain objects with Object.prototype as their prototype — your class prototype is not in the chain. Validate the structure field by field with a custom type guard (x is T).
Q Should I use instanceof or typeof?
A Use typeof for primitives (string/number/boolean, etc.) and instanceof for class instances (Date, Map, custom classes). Both are real runtime checks and compose freely.