0Pricing
TypeScript Academy · Lesson

Type Guards

Safely work with unknown or any types using type guards.

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

All lessons in this course

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