Skip to main content
A symbol is a primitive, immutable, and globally unique data type in TypeScript used to create anonymous object property keys. Introduced in ES6, symbols guarantee strict uniqueness; every invocation of the Symbol() function allocates a completely new value in memory, preventing property name collisions regardless of the execution context.

Instantiation and Syntax

Symbols are created using the Symbol() factory function. Because symbol is a primitive type, it cannot be instantiated with the new keyword.
The fundamental mechanic of a symbol is its absolute uniqueness. Even if two symbols are initialized with the identical descriptive string, they are not strictly equal.

TypeScript’s unique symbol Subtype

TypeScript introduces a nominal subtype of symbol called unique symbol. While symbol represents any symbol, unique symbol represents a specific, singular symbol tied to its declaration. To type a variable as a unique symbol, it must be declared using const or as a readonly static property on a class.
When using symbols as keys in interfaces or type aliases, TypeScript requires the symbol to be a unique symbol so the compiler can statically track the property.

The Global Symbol Registry

TypeScript supports the global symbol registry, which allows symbols to be shared across different realms (e.g., iframes, service workers) using Symbol.for() and Symbol.keyFor().
  • Symbol.for(key): Searches the global registry for a symbol with the given key. If found, it returns it; otherwise, it creates a new global symbol.
  • Symbol.keyFor(sym): Retrieves the string key for a given global symbol.

Well-Known Symbols

TypeScript includes type definitions for “well-known symbols”—built-in symbols exposed as static properties on the Symbol constructor. These are used to implement or override internal language behaviors.
Common well-known symbols include:
  • Symbol.iterator: Defines the default iterator for an object.
  • Symbol.toPrimitive: Converts an object to a corresponding primitive value.
  • Symbol.toStringTag: Defines the default string description of an object.
  • Symbol.hasInstance: Determines if a constructor object recognizes an object as its instance.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More