Equality narrowing
Equality narrowing is a feature in TypeScript that allows for more precise type checking and type inference based on the values of variables.
Equality narrowing works by analyzing the values of variables to determine whether they are equal to a specific value or not. If the value of a variable can be determined to be equal to a specific value, TypeScript can narrow the type of the variable to that specific value.
Get Danushanthi Konesalingam’s stories in your inbox
Join Medium for free to get updates from this writer.
function printSize(size: “small” | “medium” | “large”) {
if (size === “small”) {
console.log(“The size is small.”);
} else if (size === “medium”) {
console.log(“The size is medium.”);
} else {
console.log(“The size is large.”);
}
}
In this code, the size parameter is of type "small" | "medium" | "large", which means it can have one of three possible values. However, within the function, the if and else if statements use equality narrowing to determine which specific value the size variable has, and TypeScript narrows the type of size accordingly. This allows for more precise type checking and type inference within the function.
Equality narrowing can be particularly useful in cases where you are working with complex types that have multiple possible values. By using equality narrowing to determine the specific value of a variable, you can write more concise and readable code, and catch potential errors earlier in the development process.





