TypeScript Reference ยท Primitive and Special Types
TypeScript unique symbol type
Reference for TypeScript unique symbol: declare symbol constants with their own identity type, use them as property keys, and brand types safely.
A symbol value is a unique, unforgeable identifier. The general symbol type covers every symbol, so TypeScript cannot tell two of them apart. A unique symbol is a subtype of symbol that stands for one specific symbol created by one specific declaration.
That precision lets symbols act as property keys the compiler can track, and as hidden brands that stop two otherwise identical types from being mixed up. unique symbol can only be used on const declarations and on static readonly class properties.
const secret: unique symbol = Symbol("secret");
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 a: unique symbol = Symbol(); declare const b: unique symbol; class K { static readonly tag: unique symbol = Symbol(); } const c = Symbol("x"); // inferred as unique symbol for const let d = Symbol("x"); // inferred as plain symbol
| Part | Description |
|---|---|
unique symbol |
Type of exactly one symbol; a subtype of symbol. |
typeof a |
Refers to the unique symbol type of the constant a when used in type positions. |
Edge cases:
unique symbolis only allowed onconstvariables andstatic readonlyproperties.const x = Symbol()is inferred astypeof x(a unique symbol), butletor a mutable property gets the generalsymbol.- Two different declarations never have compatible unique symbol types, even if created by the same expression.
- Well-known symbols such as
Symbol.iteratorare declared as unique symbols in the standard library, which is how[Symbol.iterator]()is typed.
Usage notes
- Property keys. Use symbols to add members that cannot collide with string keys, such as internal metadata or protocol methods.
- Not enumerable by default.
Object.keys,for...inandJSON.stringifyskip symbol keys; useObject.getOwnPropertySymbols. - Branding. A
declare constunique symbol as a brand key never exists at runtime, which is cheaper than a string literal brand. - Iteration protocols.
[Symbol.iterator],[Symbol.asyncIterator]and[Symbol.toPrimitive]rely on this typing; seeIterableandIterator. - Declaration files. Library authors export
unique symbolconstants to make keys referable from type positions viatypeof. - Global registry.
Symbol.for("key")returns a shared symbol and is typed as plainsymbol.