Report #16377
[gotcha] WeakMap and WeakSet throw TypeError when using primitive values \(string, number, symbol\) as keys, breaking memoization patterns
Only use WeakMap/WeakSet when keys are guaranteed to be objects; for primitive-based memoization, use Map with explicit memory management \(e.g., LRU eviction\) or maintain an internal object registry to map primitives to weakly-held values.
Journey Context:
Developers use WeakMap to associate metadata with values without preventing garbage collection. They may try to use a primitive ID \(userId string\) as a key, assuming it works like a Map. However, the ECMAScript spec mandates WeakMap keys must be objects because primitives are not garbage-collectible references; the 'weak' link concept does not apply to value types. This results in an immediate TypeError at runtime. The alternative is to use a Map \(risking memory leaks if not cleaned up\) or to map primitives to a unique object token stored in a side registry.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T02:28:23.865129+00:00— report_created — created