DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

2 1 1 1

Day 41: Type Guards

What Are Type Guards?

Type Guards are TypeScript constructs that allow you to refine or narrow down the type of a value within a certain code block. They are especially useful when dealing with union types or unknown values.

The typeof

The simplest Type Guard in TypeScript is the typeof check. You've likely used it to differentiate between primitive types.

function logValue(value: string | number) {
  if (typeof value === 'string') {
    console.log('This is a string:', value);
  } else {
    console.log('This is a number:', value);
  }
}
Enter fullscreen mode Exit fullscreen mode

The instanceof

When working with classes and inheritance, instanceof is your go-to Type Guard.

class Animal {
  move() {
    console.log('Moving... 🚶‍♂️');
  }
}

class Bird extends Animal {
  fly() {
    console.log('Flying... 🦅');
  }
}

function moveAnimal(animal: Animal) {
  if (animal instanceof Bird) {
    animal.fly();
  } else {
    animal.move();
  }
}
Enter fullscreen mode Exit fullscreen mode

Type Guards and Unions

Unions are a common source of type-related issues. Type Guards can help ensure that your code handles union types gracefully.

type Result = { success: true; value: number } | { success: false; error: string };

function processResult(result: Result) {
  if (result.success) {
    console.log('Value is', result.value);
  } else {
    console.error('Error:', result.error);
  }
}
Enter fullscreen mode Exit fullscreen mode

With Custom Properties

The in operator is handy when dealing with objects that might have specific properties.

interface Car {
  brand: string;
  speed: number;
}

function isFast(car: Car | { name: string }): car is Car {
  return 'speed' in car;
}
Enter fullscreen mode Exit fullscreen mode

With typeof and instanceof

Type Guards can be combined to handle complex situations effectively.

function processInput(input: string | number | Animal) {
  if (input instanceof Animal) {
    input.move();
  } else if (typeof input === 'string') {
    console.log('You entered a string:', input.toUpperCase());
  } else {
    console.log('You entered a number:', input.toFixed(2));
  }
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more