Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

TypeScript WeakMap and WeakSet types

Reference for WeakMap and WeakSet in TypeScript: object-only keys, no iteration, private metadata patterns, and how the type parameters are constrained.

WeakMap<K, V> and WeakSet<T> are collections that hold their keys weakly. If nothing else references a key object, the garbage collector may remove the entry. That makes them a good fit for attaching extra data to objects you do not own, without creating a memory leak.

Because entries can disappear at any time, these collections cannot be iterated, have no size, and have no clear(). TypeScript reflects the main restriction in the types: the key type must be an object (or, in recent lib versions, a non-registered symbol). WeakMap<string, number> is a compile error.

TypeScript
const meta = new WeakMap<object, string>();

Try it

TypeScript Private metadata for objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript WeakSet and the key restriction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
class WeakMap<K extends WeakKey, V> {
  constructor(entries?: Iterable<readonly [K, V]> | null);
  delete(key: K): boolean;
  get(key: K): V | undefined;
  has(key: K): boolean;
  set(key: K, value: V): this;
}
class WeakSet<T extends WeakKey> {
  constructor(values?: Iterable<T> | null);
  add(value: T): this;
  delete(value: T): boolean;
  has(value: T): boolean;
}
Name Description
K, T The key type. It must extend WeakKey, which covers objects (and non-registered symbols in newer lib versions).
V The value type of a WeakMap. It can be anything, and is held strongly while its key is alive.

Returns: get returns V | undefined; set and add return the collection; has and delete return boolean.

Errors: using a primitive key such as a string or number is a compile error (Type 'string' does not satisfy the constraint 'WeakKey') and, if you bypass the types, a TypeError at runtime.

Usage notes

  • The second example ends with a deliberate error: WeakSet<string> fails because a string is not an object. The compiler stops the run, so the first part of that example never executes.
  • Common uses are caches keyed by object, private per-instance data, and "already visited" marks in graph walks, as in walk above.
  • You cannot list the keys or count the entries. If you need that, use a Map and manage removal yourself.
  • Values stay alive as long as the key is alive. A value that references its own key does not keep the pair alive by itself; the pair is collectable once the key is unreachable from elsewhere.
  • Garbage collection timing is not observable, so you cannot write reliable tests that wait for an entry to vanish.
  • Classes with #private fields are usually a better choice for per-instance state; a WeakMap is for data that lives outside the class.
  • WeakRef and FinalizationRegistry are related tools but have a different purpose: they let you hold a single object weakly.
  • Symbols as weak keys are only valid if they are not created with Symbol.for().