The symbol Type
What you'll learn: How TypeScript's symbol type creates unique identifiers that can never accidentally collide.
What Is a Symbol?
A symbol is a primitive type that produces a guaranteed-unique value every time you create one. Even if you create two symbols with the same description, they're completely different from each other. This makes symbols perfect for creating object property keys that won't conflict with other properties, even if someone else uses the same name.
Think of symbols like government-issued ID numbers: even if two people have the same name "John Smith," their ID numbers are always unique.
How Symbols Work
const id1: symbol = Symbol("user-id");
const id2: symbol = Symbol("user-id");
// These are NOT equal, despite identical descriptions
console.log(id1 === id2); // false
The description ("user-id") is just for debugging—it doesn't affect uniqueness.
Why Use Symbols?
Symbols shine when you need guaranteed-unique property keys:
const SECRET_TOKEN: symbol = Symbol("token");
const user = {
name: "Alice",
[SECRET_TOKEN]: "abc123"
};
// Normal property access works
console.log(user.name); // "Alice"
// Symbol property is hidden from normal enumeration
console.log(Object.keys(user)); // ["name"] - no token!
The symbol property exists but won't show up in Object.keys() or for...in loops, providing a layer of privacy.
Key Characteristics
- Immutable: Once created, a symbol never changes
- Unique: Every symbol is different from every other symbol
- Property keys: Symbols can be object property names without name collisions
Key Takeaway: The symbol type creates unique, unchangeable identifiers perfect for object properties that need guaranteed uniqueness and semi-privacy.