> ## 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.

# TypeScript WeakMap

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):

```typescript theme={"dark"}
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.

```typescript theme={"dark"}
// 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:

```typescript theme={"dark"}
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'.
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
