Table of contents
1.
Introduction
2.
What is type guard?
3.
Type guard using typeof
4.
Type guard using instanceof
5.
Type guard using in
6.
User-defined type guards
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Type Guards

Author Toohina Barua
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We know that we have to deal with many data types in our typescript. Typescript has a fantastic type system. And thus, we have features that help us efficiently deal with different types. One of the features is type guards. 
Because a variable of a union type might take on a variety of distinct types, you can use type narrowing to aid TypeScript in determining the correct variable type. Implement a type guard to limit a variable to a specified type.
This article will talk about type guards in detail. Let us dive into it!

What is type guard?

A TypeScript type guard evaluates the type of a variable using a conditional expression. It can be done by using the typeof operator followed by the variable name and comparing it to the type of variable you expect.
In short, within a conditional block, Type Guards allow you to limit down the type of a variable. There are more ways to perform type guard; let us see them in detail. 

Type guard using typeof

To evaluate the type of a variable, including number, string, and boolean, the typeof operator can be used to construct a TypeScript type guard. 
In the following code, we see how to use typeof to find whether a and b are numbers or strings. According to the if-else condition, further action is performed. 

type inputType = string | number;

function add(a: inputType, b: inputType) {
   if (typeof a === 'number' && typeof b === 'number') {
       return a + b;
   }

   if (typeof a === 'string' && typeof b === 'string') {
       return a+" "+b+"!";
   }

   if ((typeof a === 'number' && typeof b === 'string')||(typeof a === 'string' && typeof b === 'number')) {
       return "Error"
   }
  
}

console.log(add(4,5))
console.log(add("hello"," world"))
console.log(add("ooo",3))

Type guard using instanceof

The instanceof operator is recognized user-defined by TypeScript in the same way as the typeof operator is. Instanceof helps to type guard interfaces. 

The following code, instanceof helps us to check if the input given to checkType() is the interface Date or type string. 

function checkType(x: Date | string) {
   if (x instanceof Date) {
     console.log("It is a Date");
   } else {
     console.log("It is a string");
   }
}

let date = new Date()
let str: string="Hello world!"
checkType(date)
checkType(str)

Type guard using in

If a variable is a union type, TypeScript provides an additional type guard that uses the in operator to determine whether the variable has a specific property. 
In the following code, we see for the if statement since red is a property of Apple and Orange, the fruit is of type Apple | Orange. Similarly, for else, the yellow property is in Mango and Orange.  

type Apple = { red: () => void };
type Mango = { yellow: () => void };
type Orange = { red?: () => void; yellow?: () => void };
 
function move(fruit: Apple | Mango | Orange) {
  if ("red" in fruit) {
    fruit;
  } else {
    fruit;
  }
}

User-defined type guards

You can define a type guard or let TypeScript infer a type when you utilize a function with user-defined type guards. 
For instance, let’s look at the code below. We have a class, Fruit. We made a user-defined type guard using the isFruit function, which returns a boolean value. If it returns true, it means the input/argument given to the isFruit function is an instance of the class Fruit.

class Fruit {
   //field
   name: string;
   //constructor
   constructor(name:string) {
      this.name = name
   } 
   //function
   disp():void {
      console.log("The name of the fruit is: "+this.name)
   }
}
function isFruit(test: any): test is Fruit {
   return test instanceof Fruit;
 }
 function getInput(input: any) {
   if (isFruit(input)) {
         input.disp();
     } else {
         console.log("I don't know what this is: " + input);
     }
}
 getInput(new Fruit("Apple"));
getInput("Hello");

FAQs

  1. What is the use of type guard?
    Type guards are essential for narrowing types, ensuring runtime type safety, and satisfying the TS compiler.
     
  2. What goes into creating a custom type guard?
    The following are the main characteristics of a custom type guard:
    Returns a type predicate.
    Incorporates a logical statement capable of precisely determining the type of the provided variable.
     
  3. What is a type predicate?
    Type predicates are a specific return type that informs the Typescript compiler about the type of a given value. A function that accepts a single input and returns a boolean always has type predicates attached to it.

Key Takeaways

From the article, we learned about type guards and how we can perform it practically in code using typeof, in, instanceof, and user-defined type guard. 
But this is not enough; you need something extra to excel in Vue.js truly. If you want to learn more about Vue.js, you can read our articles on Vue.js or take our highly curated Web Development course.

Live masterclass