Introduction
Equality narrowing helps TypeScript understand what type a variable really is by checking if it equals something else. This makes your code safer and easier to read.
if (variable === someValue) { // TypeScript knows variable is the type of someValue here }
function printId(id: number | string) { if (typeof id === "string") { console.log(id.toUpperCase()); } else { console.log(id.toFixed(2)); } }
function checkValue(x: string | number) { if (x === "hello") { console.log("x is the string 'hello'"); } else { console.log("x is not 'hello'"); } }
function example(value: "yes" | "no" | "maybe") { if (value !== "maybe") { console.log("Value is yes or no"); } else { console.log("Value is maybe"); } }
function describe(input: number | string) { if (input === 42) { console.log("The answer to life!"); } else if (typeof input === "string" && input === "hello") { console.log("A friendly greeting."); } else { console.log("Just something else."); } } describe(42); describe("hello"); describe(10);
equality narrowing in TypeScript help you do?=== for safe type narrowing.===, which is correct. if (value == 10) { } uses loose equality, which is less safe. if (value = 10) { } is assignment, not comparison. if (value != 10) { } is inequality, not equality.function check(x: string | number) {
if (typeof x === 'string') {
return x.toUpperCase();
} else {
return x.toFixed(2);
}
}
console.log(check(3.14159));x is a string or number using typeof. For number, it calls toFixed(2).3.14159.toFixed(2) which is string "3.14".function process(value: string | number) {
if (value === 'hello') {
return value.toUpperCase();
} else {
return value.toUpperCase();
}
}value === 'hello' narrows value to string only if it equals 'hello'. Else block still has value as string or number.toUpperCase() on value in else block is unsafe because value could be number, causing runtime error.function formatValue(val: string | number | null) {
if (val === null) {
return "No value";
} else if (typeof val === 'string') {
return val.trim();
} else {
return val.toFixed(1);
}
}val === null, safely handling null case.typeof val === 'string' to narrow string, else block handles number with toFixed(1).Pass the test and this pattern moves unknown