Skip to content

Symbol unique type collision

Quick summary

You compared two Symbols with the same description but they are different unique symbols — Symbol() always creates a unique identity.

Why this happens

  • You created two symbols with Symbol('key') in different modules and compared them — they are not equal

  • You used Symbol.for('key') in one place and Symbol('key') in another, mixing global and local symbols

  • A symbol used as a property key was recreated instead of shared, so the property was never found

Minimal example

✗ Broken code
// module-a.ts
export const key = Symbol('id');
// module-b.ts
const key = Symbol('id'); // different symbol!
const obj = { [key]: 'value' };
console.log(obj[Symbol('id')]); // undefined — different symbol
✓ Fixed code
// shared.ts
export const idKey = Symbol.for('id'); // global symbol
// module-a.ts
import { idKey } from './shared';
// module-b.ts
import { idKey } from './shared';
const obj = { [idKey]: 'value' };
console.log(obj[idKey]); // 'value' — same symbol

Using Symbol.for() creates a global shared symbol, so both modules reference the same symbol and the property is found.

How to diagnose

  • Log symbol1 === symbol2 to check if they are the same symbol instance

  • Check whether symbols are created with Symbol() (unique) or Symbol.for() (global registry)

  • Use symbol.description to compare descriptions, but remember equal descriptions do not mean equal symbols

How to fix

  • Use Symbol.for('key') for symbols that need to be shared across modules — it uses the global registry

  • Export the symbol from a shared module and import it everywhere instead of recreating it

  • Use a string key instead of a symbol if cross-module sharing is needed and symbol identity is not important

How to prevent

  • Use Symbol.for() for shared symbols and Symbol() for private symbols — never mix the two for the same key

  • Export and import symbol constants rather than recreating them in each module

Related Resources

Related Glossary

Related Lessons

← Back to language