0
0
Typescriptprogramming~5 mins

Equality narrowing in Typescript

Choose your learning style9 modes available
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.
When you have a variable that can be more than one type and you want to do something only if it is a specific type.
When you want to avoid errors by making sure a value is what you expect before using it.
When you want TypeScript to help you by narrowing down types after checking equality.
When you write functions that accept different types and behave differently based on the input.
When you want clearer code that shows exactly what types are handled in each part.
Syntax
Typescript
if (variable === someValue) {
  // TypeScript knows variable is the type of someValue here
}
Use === or !== to compare values for equality or inequality.
TypeScript narrows the type inside the if block based on the comparison.
Examples
Checks if id is a string or number and narrows the type accordingly.
Typescript
function printId(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(2));
  }
}
Narrowing by checking if x equals a specific string.
Typescript
function checkValue(x: string | number) {
  if (x === "hello") {
    console.log("x is the string 'hello'");
  } else {
    console.log("x is not 'hello'");
  }
}
Using !== to narrow down the possible values.
Typescript
function example(value: "yes" | "no" | "maybe") {
  if (value !== "maybe") {
    console.log("Value is yes or no");
  } else {
    console.log("Value is maybe");
  }
}
Sample Program
This program uses equality narrowing to check the input and print different messages based on its value and type.
Typescript
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);
OutputSuccess
Important Notes
Equality narrowing works best with literal values or types that can be compared directly.
TypeScript can narrow types inside if, else if, and else blocks based on your checks.
Use strict equality (===) to help TypeScript understand your intent clearly.
Summary
Equality narrowing lets TypeScript know the exact type after checking equality.
Use === or !== to compare values and narrow types safely.
It helps write safer and clearer code by handling different types properly.