TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
The JavaScript exception "WeakSet key (or WeakMap value) 'x' must be an object or an unregistered symbol" occurs when an value of invalid type is used as a key in a WeakSet
or as a value in a WeakMap
.
Message
TypeError: Invalid value used as weak map key (V8-based) TypeError: WeakMap key 1 must be an object or an unregistered symbol (Firefox) TypeError: WeakMap keys must be objects or non-registered symbols (Safari) TypeError: Invalid value used in weak set (V8-based) TypeError: WeakSet value 1 must be an object or an unregistered symbol (Firefox) TypeError: WeakSet values must be objects or non-registered symbols (Safari)
Error type
What went wrong?
WeakSet
and WeakMap
require the keys to be garbage collectable. Only objects and non-registered symbols (that is, symbols not returned by Symbol.for()
) are valid. For more information, see Memory management. If you want to add keys that are strings, numbers, or other primitive values, you should store them in a regular Set
or Map
instead.
Examples
Invalid cases
js
new WeakSet().add(1); // TypeError
new WeakMap().set(1, {}); // TypeError
new WeakSet([1]); // TypeError
new WeakMap([[1, {}]]); // TypeError
Valid cases
js
new WeakSet().add({}); // OK
new WeakMap().set({}, 1); // OK
new Set([1]); // OK
new Map([[1, {}]]); // OK