Open In App

How to implement Type narrowing in TypeScript?

Type narrowing in TypeScript refers to refining the type of a variable within a conditional block based on runtime checks. This is achieved through techniques like typeof guards, instance checks, or property existence checks, enabling more precise typing and avoiding type errors in subsequent code execution.

These are the following ways:



Approach 1: Using typeof type guards

In TypeScript, typeof type guards use typeof to distinguish between different primitive types. For example, checking typeof variable === ‘string’ allows narrowing the type of variable to string within that conditional block.



Example: The function myFunction takes a parameter value of type string or number. If the value is a string, it’s converted to uppercase; if it’s a number, it’s formatted to 2 decimal places using toFixed().




function myFunction(value: string | number) {
    if (typeof value === 'string') {
     
        // Value is treated as string here
        console.log(value.toUpperCase());
    } else {
     
        // Value is treated as number here
        console.log(value.toFixed(2));
    }
}
 
myFunction("GeeksforGeeks");
myFunction(3.14159);

Output:

GEEKSFORGEEKS
3.14

Approach 2: Using “in” operator

The in operator in TypeScript checks for the existence of a property in an object. When used in type guards, it discerns types based on property presence. For instance, property in an object narrows the type to include the property.

Example: The function area calculates the area of a square or rectangle. It uses the in operator to distinguish between them based on property existence. If shape has sideLength, it computes the square area; otherwise, it calculates the rectangle area.




interface Square {
    sideLength: number;
}
 
interface Rectangle {
    width: number;
    height: number;
}
 
function area(shape: Square | Rectangle) {
    if ('sideLength' in shape) {
     
        // Shape is narrowed to Square here
        return shape.sideLength ** 2;
    } else {
     
        // Shape is narrowed to Rectangle here
        return shape.width * shape.height;
    }
}
 
const square: Square = { sideLength: 5 };
const rectangle: Rectangle = {
    width: 3,
    height: 4
};
 
console.log(area(square));
console.log(area(rectangle));

Output:

25
12

Article Tags :