Skip to content

TypeError: Invalid value used as weak map key

Quick summary

You called weakMap.set('key', value) with a string key — WeakMap only accepts objects as keys.

Why this happens

  • Using a string or number as a WeakMap key

  • Passing a symbol (non-registered) as a WeakMap key

  • Assuming WeakMap works like Map with any key type

Minimal example

✗ Broken code
const wm = new WeakMap();
wm.set('user-1', { name: 'Ada' }); // TypeError: Invalid value used as weak map key
✓ Fixed code
const wm = new WeakMap();
const userKey = { id: 'user-1' };
wm.set(userKey, { name: 'Ada' }); // object key — OK

WeakMap requires object keys so it can hold weak references. Using a string throws. Wrapping the key in an object satisfies the requirement.

How to diagnose

  • Read the TypeError: 'Invalid value used as weak map key'

  • Check the key type with typeof before calling set

  • Decide whether you need a Map (any key) or a WeakMap (object key)

How to fix

  • Use a regular Map if you need primitive keys

  • Wrap the primitive key in an object: { id: 'key' }

  • Use the object itself as the key, which is the WeakMap use case

How to prevent

  • Choose Map for arbitrary keys, WeakMap only for object-keyed weak references

  • Document the key type requirement when using WeakMap

Related Resources

Related Glossary

Related Lessons

← Back to language