A Symbol is a primitive value that’s guaranteed to be unique — even two symbols with the same description are not equal. That uniqueness makes them useful as non-colliding property keys.
Creating a Symbol in TypeScript
Create one with Symbol(). The string argument is just a label for debugging:
const mySymbol = Symbol('mySymbol');Using Symbols as Object Property Keys
Symbol keys don’t show up in for...in loops or Object.keys(), so they’re invisible to code that doesn’t hold a reference to the symbol:
const mySymbol = Symbol('mySymbol');
const myObject = {
[mySymbol]: 'Hello, World!'
};
console.log(myObject[mySymbol]); // Output: 'Hello, World!'Using Symbols for pseudo-private properties
Symbol-keyed fields are hidden from regular iteration, so they won’t surface by accident. That said, they’re not truly private — anyone with the symbol reference can still read the value:
const mySymbol = Symbol('mySymbol');
class MyClass {
[mySymbol] = 'private value';
getPrivateValue() {
return this[mySymbol];
}
}
const myObject = new MyClass();
console.log(myObject.getPrivateValue()); // Output: 'private value'
console.log(myObject[mySymbol]); // Output: 'private value'Conclusion
The main practical use for Symbols is avoiding property key collisions — especially useful when extending third-party objects or building library code where internal properties shouldn’t be visible to users.