TypeScript Equality Narrowing Type
Last Updated :
24 Apr, 2025
In this article, we are going to learn about Equality narrowing Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, "equality narrowing" refers to the process of narrowing the type of a variable based on equality checks or comparisons. TypeScript can use equality checks like ===, ==, !==, !=, or comparisons like <, >, <=, >= to infer more specific types. It can also use switch statements.
JavaScript’s looser equality checks with == and != also get narrowed correctly. If you’re unfamiliar, checking whether something == null actually not only checks whether it is specifically the value null - it also checks whether it’s potentially undefined. The same applies to == undefined: it checks whether a value is either null or undefined.
Example 1: In this example, We have a processValue function that takes a parameter value of type number | string. Inside the function, we use "typeof" value === 'number' to check if the value is of type 'number'. If it is, TypeScript narrows the type of value to 'number' within the if block., it's safe to perform numerical operations on value. In the else block, TypeScript narrows the type of value to 'string' because it knows that it can't be a number (due to the check-in of the if block), and it allows you to call toUpperCase() on it.
JavaScript
function processValue(value: number | string): void {
if (typeof value === 'number') {
// Inside this block, TypeScript
// narrows the type of value to 'number'
// It knows value is a number
console.log(value + 10);
} else {
// Inside this block, TypeScript
// narrows the type of value to 'string'
// It knows that the value is a string
console.log(value.toUpperCase());
}
}
// Example usage:
processValue(5);
processValue('GeeksforGeeks');