instanceof
The JavaScript operator that checks whether an object was created by a given class, by walking its prototype chain.
In more detail
err instanceof HttpError narrows err so its status is available, which is the standard way to tell error classes apart in a catch block. It only works with classes, not interfaces or type aliases, which do not exist at run time. Objects from another realm, such as an iframe, fail the check.
Related terms
- prototype chain — The linked list of objects JavaScript searches when looking up a property, which is how inheritance works under the hood.
- class — A blueprint in code that bundles data and the functions that work on it, from which objects are made.
- Error class — The JavaScript object that describes something going wrong, with a name such as TypeError and a human-readable message.
- realm — A separate JavaScript global environment with its own built-in objects, such as the one inside an iframe or a worker.
Taught in
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript