Unique Symbols
In this page:
Declaring unique symbols
A const symbol declaration gets the special unique symbol type when TypeScript needs to track its exact identity at the type level, not just treat it as the general symbol type.
Example: Declaring unique symbols
const idKey: unique symbol = Symbol("id");
console.log(idKey);
Unique Symbol as a Discriminant
Unique symbols can act as exact discriminants in a union, since each one identifies precisely one variant — TypeScript can narrow based on which specific unique symbol is present, not just "some symbol."
Example: Unique Symbol as a Discriminant
const circleTag: unique symbol = Symbol("circle");
const squareTag: unique symbol = Symbol("square");
type Shape =
| { tag: typeof circleTag; radius: number }
| { tag: typeof squareTag; side: number };
const s: Shape = { tag: circleTag, radius: 5 };
console.log(s.tag === circleTag);
Unique Symbols as Object Keys
A unique symbol can be used as a computed property key, letting an interface refer to one exact symbol-keyed property rather than an arbitrary symbol of the general symbol type.
Example: Unique Symbols as Object Keys
const idKey: unique symbol = Symbol("id");
interface Entity {
[idKey]: number;
}
const e: Entity = { [idKey]: 1 };
console.log(e[idKey]);
Exact Symbol Identity
Two unique symbols are considered different types even if their description strings are identical — this identity-based typing gives TypeScript a much stronger way to represent distinct, non-forgeable tokens.
Example: Exact Symbol Identity
const a: unique symbol = Symbol("token");
const b: unique symbol = Symbol("token");
console.log(a === (b as unknown as typeof a));
Practical Symbol Tokens
Unique symbols work well as internal tokens when an API needs strongly-typed identifiers that can never be accidentally confused with an ordinary string, number, or another unrelated symbol.
Example: Practical Symbol Tokens
const AdminToken: unique symbol = Symbol("admin");
function checkAccess(token: typeof AdminToken) {
return "Access granted";
}
console.log(checkAccess(AdminToken));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: