Sling Academy
Home/TypeScript/Equality Operators in TypeScript: A Complete Guide

Equality Operators in TypeScript: A Complete Guide

Last updated: January 07, 2024

Introduction

TypeScript, as a superset of JavaScript, enhances the language by adding static types and more robust tooling. Understanding equality operators in TypeScript is crucial for performing comparison operations that are both type-safe and reliable. This guide dives deep into equality checks in TypeScript, from primitive comparisons to complex data structures.

Understanding Equality

In TypeScript, two primary operators are used for equality checks: == and ===. The double equals operator (==) performs type coercion, trying to convert both operands to a common type before comparing them. On the other hand, the triple equals operator (===) is stricter and checks for both value and type equality, which is why it’s preferred in TypeScript.

let num: number = 5;
let str: string = '5';
console.log(num == str); // true, because of type coercion
console.log(num === str); // false, because types are different

Type-Specific Comparisons

In cases where you have variables of specific types, TypeScript’s type system enhances the predictability of equality checks. When using ===, comparisons not only check values but also ensure that the type matches, which helps catch errors at compile time.

let first: number = 5;
let second: number = '5';
// Error: Type '"5"' is not assignable to type 'number'.
console.log(first === second);

Complex Types Equality

When comparing objects in TypeScript, things get more intricate. Since objects are reference types, two objects with the same properties and values are not considered equal when compared directly with ===.

interface User {
    id: number;
    name: string;
}

let user1: User = { id: 1, name: 'John' };
let user2: User = { id: 1, name: 'John' };
console.log(user1 === user2); // false, because they are different references

Custom Equality Checks for Objects

To accurately check for equality between objects, we need to implement a custom function that compares individual properties.

function areUsersEqual(userA: User, userB: User): boolean {
    return userA.id === userB.id && userA.name === userB.name;
}

console.log(areUsersEqual(user1, user2)); // true

Generics and Equality

Using generics in TypeScript allows for creating reusable components. When it comes to equality, generics add a layer of complexity as they introduce type variables that can represent any type.

function isEqual<T>(a: T, b: T): boolean {
    if (typeof a === 'object' && typeof b === 'object') {
        return JSON.stringify(a) === JSON.stringify(b);
    }
    return a === b;
}

console.log(isEqual({ id: 1 }, { id: 1 })); // true
console.log(isEqual('hello', 'hello')); // true

Conclusion

Mastering equality operators in TypeScript adds precision and reliability to your code. Throughout this guide, we examined various facets of equality checks, from simple primitives to more complex generic types. Consistently using === will maintain type integrity and using custom equality functions will help ensure accurate comparisons of complex structures. Remember, thoughtful comparisons will lead to clearer, more maintainable, and error-resistant code.

Next Article: Type Declaration Files in TypeScript: A Complete Guide

Previous Article: Null and Undefined in TypeScript: A Practical Guide

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)