How to usetypeof type guards in Typescript

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().

Javascript




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("w3wiki");
myFunction(3.14159);


Output:

w3wiki
3.14

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:

Table of Content

  • Using typeof type guards
  • Using in operator

Similar Reads

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....

Approach 2: Using “in” operator

...