Skip to main content
A Set in TypeScript is a generic, iterable collection of unique values. It wraps the native ECMAScript 6 Set object with TypeScript’s static type system, ensuring that all elements within the collection conform to a specified type parameter <T>. Uniqueness is evaluated using the SameValueZero algorithm, meaning NaN is considered equal to NaN, and duplicate values are silently ignored during insertion.

Instantiation and Type Inference

A Set can be instantiated empty with an explicit generic type argument, or initialized with an iterable object (like an Array), from which TypeScript will infer the type.

Core API

The Set prototype provides a standard set of methods for mutation and inspection.
  • add(value: T): this: Appends a new element with the specified value. Returns the Set instance, enabling method chaining.
  • has(value: T): boolean: Evaluates whether an element with the specified value exists within the collection.
  • delete(value: T): boolean: Removes the specified element. Returns true if the element existed and was removed, or false if it did not exist.
  • clear(): void: Removes all elements from the Set.
  • size: number: A read-only property returning the total count of elements.

Object Reference Equality

When storing complex types (objects, arrays, functions), uniqueness is determined by memory reference, not structural equality. Two structurally identical objects are treated as distinct elements.

Iteration

Set objects are natively iterable and maintain insertion order. They can be traversed using for...of loops or the built-in forEach method.

Native Set Operations (TypeScript 5.5+ / ES2024)

Modern TypeScript supports native mathematical set operations, returning new Set instances without mutating the originals.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More