Sub topic 7
Narrowing with `instanceof`
This chapter assumes basic TypeScript syntax, union types, and JavaScript control flow. You should also know that TypeScript types are removed when code runs. The JavaScript runtime can inspect objects, but it cannot inspect interfaces or type aliases.
The instanceof operator checks whether an object was created by a particular class constructor, or by a constructor in its prototype chain. TypeScript uses that check as a type guard. A type guard is a runtime check that lets the compiler narrow a value to a more specific type.
Checking class instances
Suppose a function accepts either a custom error class or a string. The instanceof check narrows the value inside each branch:
class NetworkError extends Error {
constructor(
message: string,
readonly statusCode: number
) {
super(message);
this.name = "NetworkError";
}
}
function describeFailure(failure: NetworkError | string): string {
if (failure instanceof NetworkError) {
return `${failure.message} (HTTP ${failure.statusCode})`;
}
return `Failure: ${failure}`;
}
console.log(describeFailure(new NetworkError("Unavailable", 503)));
console.log(describeFailure("Invalid request"));Inside the if block, failure is a NetworkError, so message and statusCode are available. After the if, TypeScript knows that the remaining possibility is string.
The check also works with a base class:
function messageOf(error: Error | string): string {
return error instanceof Error ? error.message : error;
}A NetworkError is also an Error, because it extends Error. Therefore, an instance of NetworkError passes the error instanceof Error check.
How the control flow works
TypeScript follows the possible paths through your code:
The right-hand side of instanceof must be a runtime constructor, such as a class or built-in constructor. It cannot be an interface:
interface User {
name: string;
}
// Invalid: User exists only during type checking.
// value instanceof UserThe interface is erased from the emitted JavaScript. There is no User constructor for the runtime to check.
`instanceof` and built-in objects
You can use instanceof with built-in classes such as Date, Map, and Error:
function formatDate(value: Date | string): string {
if (value instanceof Date) {
return value.toISOString();
}
return value;
}This distinguishes a real Date object from a string that happens to contain a date. It does not validate arbitrary data from JSON. JSON parsing creates plain objects, not instances of your custom classes.
Common failure modes
instanceof can produce unexpected results when values cross JavaScript realms, such as between a page and an iframe. The same built-in class may have different constructors in those realms. Some libraries also create objects with unusual prototypes.
For data whose shape matters more than its origin, use property checks or a user-defined type guard. For example, checking that an object has a numeric statusCode can be more reliable than requiring it to be a NetworkError instance.
Use instanceof when these conditions are true:
- The value is expected to be an instance of a known class.
- The constructor exists at runtime.
- The prototype relationship is stable in your environment.
- Class identity matters more than just having matching properties.
Exercise
What type does TypeScript assign to value in the if branch, and why?
class FileError extends Error {
constructor(
message: string,
readonly path: string
) {
super(message);
}
}
function report(value: FileError | number): string {
if (value instanceof FileError) {
return value.path;
}
return value.toFixed(0);
}
Show answer
TypeScript narrows value to FileError in the if branch because FileError is the constructor tested by instanceof. After the branch, the remaining type is number.