0Pricing
TypeScript Academy · Lesson

Type Guards

Safely work with unknown or any types using type guards.

Type Guards is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Type Guards

Welcome to the next lesson! In this lesson, you’ll learn about type guards, a powerful feature in TypeScript that allows you to narrow down types during runtime. Type guards ensure your code is type-safe and avoids errors. Let’s dive in!

Type Guards — illustration 1

2

What Are Type Guards?

A type guard is a function or construct that determines the type of a variable at runtime. It allows TypeScript to narrow a variable’s type within a specific block of code.

Example:

Task: Write a function that uses a type guard to check if a value is a number.

function isString(value: unknown): boolean {
  return typeof value === "string";
}

function printLength(value: unknown): void {
  if (isString(value)) {
    console.log(value.length); 
// TypeScript knows 'value' is a string here
  } else {
    console.log("Value is not a string");
  }
}

printLength("Hello"); 
// Output: 5
printLength(42); 
// Output: Value is not a string

3

Using typeof for Primitives

You can use the typeof operator to check the type of primitive values like strings, numbers, and booleans.

Example:

Task: Use typeof to differentiate between a string and a number in a function.

function printValue(value: string | number): void {
  if (typeof value === "string") {
    console.log(`String value: ${value}`);
  } else {
    console.log(`Number value: ${value}`);
  }
}

printValue("Hello"); 
// Output: String value: Hello
printValue(42); 
// Output: Number value: 42

4

Using instanceof for Classes

The instanceof operator checks whether an object is an instance of a specific class. Example:

Task: Use instanceof to handle different class instances in a function.

class Dog {
  bark(): void {
    console.log("Woof!");
  }
}

class Cat {
  meow(): void {
    console.log("Meow!");
  }
}

function makeSound(animal: Dog | Cat): void {
  if (animal instanceof Dog) {
    animal.bark();
  } else {
    animal.meow();
  }
}

let dog = new Dog();
let cat = new Cat();
makeSound(dog); 
// Output: Woof!
makeSound(cat); 
// Output: Meow!

5

Using Custom Type Guards

You can create custom type guard functions using a return type of value is Type. Example:

interface Car {
  make: string;
  model: string;
}

interface Bike {
  brand: string;
  type: string;
}

function isCar(vehicle: Car | Bike): vehicle is Car {
  return (vehicle as Car).make !== undefined;
}

function printVehicle(vehicle: Car | Bike): void {
  if (isCar(vehicle)) {
    console.log(`Car: ${vehicle.make} ${vehicle.model}`);
  } else {
    console.log(`Bike: ${vehicle.brand} ${vehicle.type}`);
  }
}

let car: Car = { make: "Toyota", model: "Corolla" };
let bike: Bike = { brand: "Yamaha", type: "Sport" };

printVehicle(car); 
// Output: Car: Toyota Corolla
printVehicle(bike);
 // Output: Bike: Yamaha Sport

6

Discriminated Unions

Discriminated unions use a common property to differentiate between types. Example:

interface Circle {
  kind: "circle";
  radius: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

type Shape = Circle | Rectangle;

function calculateArea(shape: Shape): number {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.width * shape.height;
  }
}

let circle: Circle = { kind: "circle", radius: 5 };
let rectangle: Rectangle = { kind: "rectangle", width: 10, height: 20 };

console.log(calculateArea(circle)); 
// Output: 78.53981633974483
console.log(calculateArea(rectangle)); 
// Output: 200

7

Exhaustiveness Checking

Exhaustiveness checking ensures that all possible cases in a discriminated union are handled. Example:

function getShapeInfo(shape: Shape): string {
  switch (shape.kind) {
    case "circle":
      return `Circle with radius ${shape.radius}`;
    case "rectangle":
      return `Rectangle with dimensions ${shape.width}x${shape.height}`;
    default:
      // This line ensures all cases are handled
      const _exhaustiveCheck: never = shape;
      return _exhaustiveCheck;
  }
}

8

Common Mistakes

Here are some common mistakes when using type guards:

  • Forgetting to include all cases in a union type.
  • Not using a type guard in all branches of conditional logic.
  • Misusing as to cast types without proper checks.

Tip: Always use type guards to narrow down types before accessing their specific properties or methods!

9

10

Great Job!

Congratulations! You’ve learned how to use type guards in TypeScript to narrow down types during runtime and ensure type safety. Type guards are essential for handling complex union types and creating robust, error-free code. In the next lesson, we’ll explore advanced mapped types. Let’s keep coding!

Type Guards — illustration 10

Frequently asked questions

Is the “Type Guards” lesson free?

Yes — the full text of “Type Guards” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type Guards”?

Safely work with unknown or any types using type guards. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type Guards” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generics
  2. Type Aliases and Interfaces
  3. Utility Types
  4. Type Guards
← Back to TypeScript Academy