Skip to main content
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):

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.

Compile-Time Enforcement

TypeScript will actively prevent the insertion of invalid key types that violate the WeakKey constraint:
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More