Skip to lesson

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.

Beginner to advanced·14 min·Combining and narrowing types·Updated 2026-11-24

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:

typescript
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"));
result
2026-11-24 tomorrow

Inside the if, value is a Date, so toISOString is available. A common use is with caught errors:

typescript
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"));
result
disk full plain text

Remember 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:

typescript
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" }));
result
splash flap

This 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:

typescript
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 }));
result
Tom says meow Rex says woof

When 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:

typescript
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);
}
result
7

Filtering arrays with a type guard

A type guard also makes filter produce a precise array type:

typescript
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()));
result
[ '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:

typescript
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));
}
result
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.

Next: Discriminated unions and exhaustive checks.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 Which narrows an unknown value to a Date?
02 What does "swim" in animal check?
03 What does the return type value is string tell the compiler?
04 What is the risk of a user-defined type guard?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses