Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A WeakSet is a built-in collection that stores unique, weakly held object references. Unlike a standard Set, a WeakSet does not prevent its constituent objects from being reclaimed by the garbage collector if no other strong references to those objects exist in memory. In TypeScript, WeakSet is defined with a generic type parameter T that is strictly constrained to object (and symbol in ES2023+).
interface WeakSet<T extends object> {
    add(value: T): this;
    delete(value: T): boolean;
    has(value: T): boolean;
}

Core Characteristics

1. Object-Only Values Primitives (string, number, boolean, null, undefined) are strictly prohibited. Attempting to add a primitive will result in a TypeScript compiler error.
const weakSet = new WeakSet<object>();

const obj = { id: 1 };
weakSet.add(obj); // Valid

// TypeScript Error: Argument of type 'string' is not assignable to parameter of type 'object'.
weakSet.add("string"); 
2. Weak References and Garbage Collection The references held by the WeakSet are ephemeral. If the JavaScript engine’s garbage collector destroys an object because it is no longer referenced anywhere else in the application, that object is implicitly and automatically removed from the WeakSet. 3. Non-Iterability Because garbage collection is non-deterministic, the exact contents of a WeakSet cannot be known or safely enumerated at any given moment. Consequently, WeakSet does not implement the Iterable interface.
  • It lacks iteration methods (forEach, keys, values, entries).
  • It cannot be used in for...of loops.
  • It does not possess a size property.
  • It cannot be cleared entirely (no clear() method).

Syntax and API Visualization

A WeakSet exposes only three methods for interacting with its contents: add, has, and delete.
interface Process {
    pid: number;
}

// Instantiation with a specific object type
const activeProcesses = new WeakSet<Process>();

let proc1: Process | null = { pid: 1001 };
let proc2: Process | null = { pid: 1002 };

// Narrowing types to satisfy strictNullChecks before passing to WeakSet methods
if (proc1 && proc2) {
    // 1. add(value) - Appends a new object to the WeakSet
    activeProcesses.add(proc1);
    activeProcesses.add(proc2);

    // 2. has(value) - Returns a boolean asserting whether an object is present
    console.log(activeProcesses.has(proc1)); // true

    // 3. delete(value) - Removes the specified object from the WeakSet
    activeProcesses.delete(proc2);
    console.log(activeProcesses.has(proc2)); // false
}

// Implicit removal via Garbage Collection
proc1 = null; 
// The { pid: 1001 } object is now unreachable.
// Once the garbage collector runs, it is purged from activeProcesses.
Master TypeScript with Deep Grasping Methodology!Learn More