← Back to TypeScript Course | Chapter 21: Symbols and Iterators | Lesson 2 of 6

Unique Symbols

A unique symbol is a symbol type that has a specific identity at the type level. TypeScript uses unique symbols when a particular symbol constant must be distinguishable from every other symbol.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.