TypeScript Reference ยท Primitive and Special Types
The TypeScript symbol type
Reference for the symbol type in TypeScript: Symbol(), Symbol.for, well-known symbols, symbol keys on objects, unique symbol and typing iterators.
symbol is a primitive type whose values are guaranteed to be unique. You create one by calling Symbol("description"); no two calls return the same value, even with the same description. Symbols are mainly used as property keys that cannot collide with ordinary string keys, and as hooks into the language through the well-known symbols.
A symbol that you declare with const can get the more precise type unique symbol, which lets TypeScript use it as a key in types and declarations.
const id: symbol = Symbol("id"); const tag = Symbol("tag"); // type: typeof tag (a unique symbol)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
const s: symbol = Symbol("label"); const key: unique symbol = Symbol("key"); interface Holder { [key]: string } // only unique symbols can be used this way
| Part | Description |
|---|---|
Symbol(description?) |
Creates a new unique symbol. Do not call it with new (it throws TypeError). |
Symbol.for(key) |
Looks up or creates a symbol in the global registry, shared across realms. |
Symbol.keyFor(sym) |
Returns the registry key, or undefined for non-registered symbols. |
sym.description |
The optional description string. |
Symbol.iterator, asyncIterator, hasInstance, toPrimitive, toStringTag, ... |
Well-known symbols that customize language behavior. |
Usage notes
symbolvsunique symbol. Aconst x = Symbol()gets its own type, soxcan name a property in an interface or class. Alet, a parameter or a function result is plainsymbol.- Keys. Symbol keys are skipped by
Object.keys,for...inandJSON.stringify, butObject.getOwnPropertySymbolsandReflect.ownKeyslist them. They give soft privacy, not security. - No implicit string conversion.
"" + symthrowsTypeError; usesym.toString()orsym.description. - Indexed access.
obj[sym]on a plainsymbolfails with an implicit-any error unless the object has a symbol index signature ([key: symbol]: T). - Library targets. Well-known symbols need the matching
lib(es2015.symbol.wellknownis included in modern targets). - Use cases. Metadata keys, brand fields, protocol hooks, private-ish markers across modules.