TypeScript · Lesson 17 of 42
Type guards: instanceof, in and custom predicates
Narrow object types with instanceof and the in operator, and write your own type guard functions that return value is Type.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will have a full set of tools for narrowing object types, not only simple values like strings and numbers. You will also be able to write your own checks and teach the compiler what they prove.
instanceof
When a value might be one of several classes, instanceof narrows it. It also works for built-in classes such as Date and Error:
function formatDate(value: Date | string): string {
if (value instanceof Date) {
return value.toISOString().slice(0, 10);
}
return value;
}
console.log(formatDate(new Date("2026-11-24T10:00:00Z")), formatDate("tomorrow"));2026-11-24 tomorrowInside the if, value is a Date, so toISOString is available. A common use is with caught errors:
function message(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
console.log(message(new Error("disk full")), message("plain text"));disk full plain textRemember that instanceof is a run-time check on real objects. It cannot work with types or interfaces, because those do not exist when the program runs.
The in operator
For plain objects with no class, check for a distinctive property with in. The compiler narrows a union to the members that could have it:
type Fish = { swim: () => string };
type Bird = { fly: () => string };
function move(animal: Fish | Bird): string {
if ("swim" in animal) {
return animal.swim();
}
return animal.fly();
}
console.log(move({ swim: () => "splash" }), move({ fly: () => "flap" }));splash flapThis works well when each member of the union has at least one property the others lack. When members look too alike, a better design is a tag property, which the next lesson, on discriminated unions, builds.
User-defined type guards
Sometimes a check is too complex for the compiler to follow. For example, a separate function may perform the check. Write a type guard: a function whose return type is a type predicate, written parameter is Type:
type Cat = { name: string; meows: true };
type Dog = { name: string; barks: true };
function isCat(pet: Cat | Dog): pet is Cat {
return "meows" in pet;
}
function speak(pet: Cat | Dog): string {
if (isCat(pet)) {
return `${pet.name} says meow`;
}
return `${pet.name} says woof`;
}
console.log(speak({ name: "Tom", meows: true }), speak({ name: "Rex", barks: true }));Tom says meow Rex says woofWhen isCat returns true, the compiler treats pet as a Cat inside the if. In the rest of the function, it knows pet must be a Dog. Type guards are especially useful for unknown values, such as data from outside the program:
type Point = { x: number; y: number };
function isPoint(value: unknown): value is Point {
return (
typeof value === "object" &&
value !== null &&
"x" in value &&
"y" in value &&
typeof value.x === "number" &&
typeof value.y === "number"
);
}
const input: unknown = JSON.parse('{"x": 3, "y": 4}');
if (isPoint(input)) {
console.log(input.x + input.y);
}7Filtering arrays with a type guard
A type guard also makes filter produce a precise array type:
const values: (string | number)[] = [1, "a", 2, "b"];
const words = values.filter((v): v is string => typeof v === "string");
console.log(words.map(w => w.toUpperCase()));[ 'A', 'B' ]Without the predicate, words would still be (string | number)[], and toUpperCase would fail on its elements.
A guard is a promise
The compiler trusts a type predicate completely. It does not verify the logic inside:
type Point = { x: number; y: number };
function isPointBad(value: unknown): value is Point {
return true;
}
const data: unknown = "not a point";
if (isPointBad(data)) {
console.log(data.x.toFixed(1));
}TypeError: Cannot read properties of undefined (reading 'toFixed')This compiles, and then crashes at run time, because the guard lies. When you write a guard, make the check match the type exactly, and test it with values that should fail as well as ones that should pass.
Common mistakes
Using instanceof with interfaces. Interfaces and type aliases do not exist at run time. Use in, a tag property or a custom guard.
Writing a guard that checks too little. A predicate that only checks typeof value === "object" does not prove the shape.
Forgetting null in object checks. typeof null === "object", so also check value !== null.
Trusting data from outside without a guard. JSON, form data and API responses are unknown in spirit. Check them before use.
Exercise
Write isString(value: unknown): value is string and use it inside a function that accepts unknown. Then write isUser(value: unknown): value is { name: string; age: number }, test it with a valid object, a missing field, a wrong type and null. Use it to filter an unknown[] into an array of users.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.