TypeScript / TypeScript Enums and Tuples

Type Guards

Welcome to this tutorial on Type Guards. Type Guards are a powerful feature in TypeScript that allow you to check and enforce the type of a variable.

Tutorial 4 of 4 4 resources in this section

Section overview

4 resources

Covers working with enums and tuples to define constant sets of values and fixed-length arrays.

Tutorial: Type Guards in TypeScript

1. Introduction

1.1 Tutorial's Goal

This tutorial aims to provide a comprehensive understanding of Type Guards in TypeScript. By the end of this tutorial, you will be able to use Type Guards effectively in your TypeScript projects.

1.2 Learning Outcomes

  • Understand what Type Guards are and why they are useful.
  • Learn how to implement Type Guards in TypeScript.
  • Be able to use Type Guards effectively in your TypeScript code.

1.3 Prerequisites

  • Basic knowledge of TypeScript.
  • Familiarity with variables and types in TypeScript.

2. Step-by-Step Guide

Type Guards are a feature in TypeScript that allows you to check the type of a variable at runtime. This is particularly useful in cases where the type of a variable could be one of several possible types.

2.1 Using typeof

One of the simplest ways to create a Type Guard is by using the typeof operator. This operator can be used to check the type of a variable.

let variable: any = 'I am a string';

if (typeof variable === 'string') {
  // In this block, TypeScript knows that `variable` is a string.
  console.log(variable.length); // Outputs: 13
}

In the above example, inside the if block, TypeScript knows that variable is a string. Thus it allows using string methods on variable.

2.2 Using instanceof

Another method of creating a Type Guard is to use the instanceof operator. This operator checks if an object is an instance of a specific class.

class Dog {
  bark() {
    console.log('Woof!');
  }
}

class Cat {
  meow() {
    console.log('Meow!');
  }
}

let pet: Dog | Cat;

if (pet instanceof Dog) {
  pet.bark(); // Outputs: "Woof!"
} else {
  pet.meow(); // Outputs: "Meow!"
}

In the above example, TypeScript is able to determine the type of pet using the instanceof operator.

3. Code Examples

3.1 Example 1: Type Guard using typeof

function process(input: string | number) {
  if (typeof input === "string") {
    return input.toUpperCase(); // input is treated as a string here
  } else {
    return input.toFixed(2); // input is treated as a number here
  }
}

console.log(process("Hello")); // Outputs: "HELLO"
console.log(process(100)); // Outputs: "100.00"

In this example, the function process takes an input which can be a string or number. Inside the function, a type guard is used with typeof to check the type of the input.

3.2 Example 2: Type Guard using instanceof

class Rectangle {
  constructor(public width: number, public height: number) {}
  area() {
    return this.width * this.height;
  }
}

class Circle {
  constructor(public radius: number) {}
  area() {
    return Math.PI * this.radius * this.radius;
  }
}

function getArea(shape: Rectangle | Circle) {
  if (shape instanceof Rectangle) {
    return shape.area(); // shape is treated as Rectangle here
  } else {
    return shape.area(); // shape is treated as Circle here
  }
}

console.log(getArea(new Rectangle(5, 10))); // Outputs: 50
console.log(getArea(new Circle(7))); // Outputs: 153.93804002589985

In this example, the function getArea takes a shape which can be an instance of Rectangle or Circle. Inside the function, a type guard is used with instanceof to check the type of the shape.

4. Summary

In this tutorial, you have learned about Type Guards in TypeScript and how to use them. You've seen how to use the typeof and instanceof operators to create Type Guards.

Next steps for learning would be to try using Type Guards in your own TypeScript projects and see how they can help you write safer, more robust code.

5. Practice Exercises

Exercise 1

Write a function that takes a parameter that can either be a string or an array of strings. If it's a string, convert it to uppercase. If it's an array, return the length of the array.

Exercise 2

Write a class for Square and Triangle each having a method perimeter. Create a function that takes an object which can be an instance of Square or Triangle and returns its perimeter.

Solutions

Exercise 1:

function process(input: string | string[]) {
  if (typeof input === "string") {
    return input.toUpperCase();
  } else {
    return input.length;
  }
}

console.log(process("Hello")); // Outputs: "HELLO"
console.log(process(["Hello", "World"])); // Outputs: 2

Exercise 2:

class Square {
  constructor(public side: number) {}
  perimeter() {
    return this.side * 4;
  }
}

class Triangle {
  constructor(public side: number) {}
  perimeter() {
    return this.side * 3;
  }
}

function getPerimeter(shape: Square | Triangle) {
  return shape.perimeter();
}

console.log(getPerimeter(new Square(5))); // Outputs: 20
console.log(getPerimeter(new Triangle(3))); // Outputs: 9

Keep practicing with other types and classes to get more comfortable with Type Guards!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help