JT Archie

# TypeScript: Type Guards for Safer Code

TypeScript type guards are a powerful feature that allows you to ensure type safety within your code. They help you avoid runtime errors by checking the types of your variables before performing any operations. This guide demonstrates how to use type guards to make your TypeScript code more reliable and maintainable.

Consider a simple example where you have a union type Person that can be either a Student or a Teacher:

interface Student {
  role: "student";
  grade: number;
}

interface Teacher {
  role: "teacher";
  subject: string;
}

type Person = Student | Teacher;

You want to create a function that takes a Person as an argument and logs their information. Without type guards, you may face issues with accessing properties that don’t exist on one of the types:

function logPersonInfo(person: Person) {
  console.log(`Role: ${person.role}`);
  // These lines will cause a TypeScript error because the properties might not exist on the type
  console.log(`Grade: ${person.grade}`);
  console.log(`Subject: ${person.subject}`);
}

With type guards, you can ensure type safety by checking the type of the person before accessing the properties: By using type guards, you can ensure that your TypeScript code is type-safe, reducing the likelihood of runtime errors and improving code reliability and maintainability.

function logPersonInfo(person: Person) {
  console.log(`Role: ${person.role}`);

  if (person.role === "student") {
    console.log(`Grade: ${person.grade}`);
  } else if (person.role === "teacher") {
    console.log(`Subject: ${person.subject}`);
  }
}

const student: Student = { role: "student", grade: 8 };
const teacher: Teacher = { role: "teacher", subject: "Math" };

logPersonInfo(student); // Output: Role: student, Grade: 8
logPersonInfo(teacher); // Output: Role: teacher, Subject: Math

# Follow for more tips