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 WeakMap is a built-in generic collection of key-value pairs where the keys are strictly object references (or non-registered symbols) and are held weakly. This weak reference means that if no other strong references to the key object exist in the execution environment, the JavaScript engine’s garbage collector (GC) will automatically reclaim the key’s memory and implicitly remove the corresponding entry from the map. In TypeScript, WeakMap is strongly typed using generics to enforce the types of both the keys and the values at compile time.

Type Signature

TypeScript defines the WeakMap interface using the WeakKey constraint (which resolves to object | symbol in modern ECMAScript targets):
interface WeakMap<K extends WeakKey, V> {
    delete(key: K): boolean;
    get(key: K): V | undefined;
    has(key: K): boolean;
    set(key: K, value: V): this;
}

Core Characteristics

  • Key Constraints: Keys must satisfy the K extends WeakKey constraint. Attempting to use primitive values (like string, number, or boolean) as keys will result in a compile-time error.
  • Non-Iterability: Because the garbage collector operates non-deterministically, the state of a WeakMap cannot be observed. Consequently, WeakMap does not implement the Iterable interface. It lacks methods like keys(), values(), entries(), and forEach(), and it does not have a size property.
  • Memory Management: The value associated with a key is held strongly by the WeakMap only as long as the key itself is strongly referenced elsewhere. Once the key is garbage collected, the value is also eligible for garbage collection (unless referenced elsewhere).

Syntax and API

When instantiating a WeakMap, you can explicitly declare the generic type parameters to enforce strict typing for the set and get methods.
// Define a specific type for the key
interface NodeConfig {
    id: string;
    active: boolean;
}

// Instantiate the WeakMap with explicit types
const nodeMetadata = new WeakMap<NodeConfig, number>();

// Valid key instantiation
let nodeRef: NodeConfig | null = { id: "node_01", active: true };

// Narrow the type to satisfy strictNullChecks before passing to WeakMap methods
if (nodeRef !== null) {
    // 1. set(key, value) - Adds or updates an entry. Returns the WeakMap instance.
    nodeMetadata.set(nodeRef, 1024);

    // 2. get(key) - Retrieves the value. Returns V | undefined.
    const size: number | undefined = nodeMetadata.get(nodeRef); 

    // 3. has(key) - Checks for the existence of a key. Returns a boolean.
    const exists: boolean = nodeMetadata.has(nodeRef); 

    // 4. delete(key) - Removes the key-value pair. Returns a boolean indicating success.
    nodeMetadata.delete(nodeRef);
}

// Removing the strong reference allows the GC to sweep the object
// and implicitly clear the WeakMap entry.
nodeRef = null; 

Compile-Time Enforcement

TypeScript will actively prevent the insertion of invalid key types that violate the WeakKey constraint:
const invalidMap = new WeakMap<string, number>(); 
// Error: Type 'string' does not satisfy the constraint 'WeakKey'.

const validMap = new WeakMap<object, string>();
validMap.set("key", "value"); 
// Error: Argument of type 'string' is not assignable to parameter of type 'object'.
Master TypeScript with Deep Grasping Methodology!Learn More