Table of contents
1.
Introduction
2.
Type Guards
3.
Equality Narrowing
4.
Discriminated Unions
5.
Narrowing Using in Operator
6.
Narrowing Using Assignment
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

TypeScript Type Narrowing

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A variable is a uniquely named location used to store data in any programming language. In Typescript, the variable must be declared before being used, using the keyword let or var. The syntax for declaring variables in Typescript is a little different from other languages and looks something like this,

var [variable_name] : [type_of_variable] = [value] ;

For example

var name: string = “Ninja”; //Both the value and the type is specified
var name: string; //only the type is mentioned
var name = “Ninja”; //only the value is mentioned
var name; //neither the value nor the type is mentioned, only the variable is declared

All of these are correct methods of initializing a variable.

 

Type Narrowing refers to the process of moving a variable from a less precise data type to a more exact data type. Type Narrowing can be implemented in many ways, and we will look at all of them in this article. For example, if no data type is mentioned, the variable will be allotted any type.

Type Guards

Type Guards are the most commonly used tools to achieve Type Narrowing. It is used to check whether a variable is a certain type or not. Let us look at an example to understand Type Guards better,

function Narrow(input: string | number){
    if(typeof input === "string"){
        console.log("Input is a string");
    }
    else{
        console.log("Input is a number");
    }
};
Narrow("Hey Ninja");
Narrow(1111);

The input could take either a string or a number type in the above example. Using Type Guards, we performed Narrowing, such that when the input type is a string, the if block is executed. Otherwise, we move to the else block.

 

We can also implement it to differentiate between a truthy or falsy i.e. Null or Undefined, data types. Let us look at an example,

function Narrow(input?:string){
    if(input){
        console.log("Input is a string");
    }
    else{
        console.log("Input is undefined");
    }
};
Narrow("Hey Ninja");
Narrow();

Equality Narrowing

This type of Narrowing works on the principle that if two variables are equal, their types are also equivalent. Let us look at an example and see how this type of Narrowing works.

function Narrow(input: string|number, compare: number){
    if(input === compare){
        console.log("Input is a number");
    }
    else{
        console.log("Input is a string");
    }
};
Narrow("1", 1);
Narrow(1, 1);

Using the above example, it is clear that even if we provided the same value but different types, the else block is executed. When the same value and data types are provided, the if block is performed.

Discriminated Unions

In this Narrowing mechanism, an object is created with a literal member, specifically used to discriminate between two unions. Let us look at an example for the same.

type fish = {
    trait: "swim",
    species: string;
}
type bird = {
    trait: "fly",
    species: string;
}
function Narrow(trait: fish | bird){
    if(trait.trait === "swim"){
        console.log("Species of fish is" +trait.species);
    }
    else{
        console.log("Species of bird is" +trait.species);
    }
};

In the above code, we create two objects, and the trait literal member is used for discriminating between the objects.

Narrowing Using in Operator

The in operator checks if an object has a property with the mentioned name in it. Let us take an example to understand this concept better.

type Circle = {
    Radius: number;
}
type Square = {
    side : number
}
function Area(input: Circle|Square){
    if("side" in input){
        var side = input.side;
        return side*side
    }
    else{
        var radius=input.radius
        return 3.14*radius*radius;
    }
}

In the above example, we used the in operator to check if the input contains the side attribute. If yes, we determine that the image is a square. Otherwise, the image is a circle.

Narrowing Using Assignment

The data type can also be narrowed down to a more specific data type by assigning the variable a value. For instance, if we have a variable that is a union of two data types, say string and number. So if we assign the variable a string value, it will be narrowed down to a string data type and the same for a numerical value. For example,

let variable: string | number;
variable = "Hey Ninja";
console.log(typeof(variable));
variable = 1234;
console.log(typeof(variable));

FAQs

  1. What is Type Narrowing?
    Type Narrowing refers to the process of moving a variable from a less precise data type to a more exact data type. 
     
  2. Why is Type Narrowing used?
    In Typescript, sometimes the variables might contain a union of data types. To get a more specific data type, we use Type Narrowing.

Key Takeaways

This Blog covered all the necessary points about Narrowing in Typescript, discussing in-depth its functionality and different methods of the appliance of Narrowing. And also its implementation in Typescript.

Don't stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.

Live masterclass