Symbols were introduced in ECMAScript 6 (ES6) as a new primitive data type in JavaScript. Symbols are unique and immutable values that can be used as keys for object properties. They are often used to add metadata to objects, to define non-colliding property keys, or to create constants.

Creating a Symbol in TypeScript

In TypeScript, you can create a Symbol using the Symbol() function. Here is an example:

const mySymbol = Symbol('mySymbol');

In this example, mySymbol is a new Symbol value with a description of “mySymbol”. The description is optional, and it is mainly used for debugging and logging purposes.

Using Symbols as Object Property Keys

One of the main use cases for Symbols is to use them as keys for object properties. When a Symbol is used as a key, it is guaranteed to be unique and cannot be accidentally overwritten or accessed by other parts of the code.

Here is an example of using a Symbol as a key for an object property:

const mySymbol = Symbol('mySymbol');

const myObject = {
  [mySymbol]: 'Hello, World!'
};

console.log(myObject[mySymbol]); // Output: 'Hello, World!'

In this example, mySymbol is used as a key for the myObject property. The value of the property is the string “Hello, World!”. The square brackets syntax is used to define a computed property name, where the property name is evaluated at runtime.

Using Symbols for pseudo-private properties

Another common use case for Symbols is to create pseudo-private properties. Symbol-keyed fields are not listed in regular object key iteration, so they are less likely to be accessed by accident. However, they are not truly private.

Here is an example of creating a private object property using a Symbol:

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'

In this example, mySymbol is used to define a symbol-keyed property for MyClass. The getPrivateValue() method returns that value. This pattern helps avoid collisions, but it is not true privacy because code with access to the same symbol can still read the property.

Conclusion

Symbols are a powerful and useful addition to the JavaScript language. They provide a way to create unique values that can be used as keys for object properties, to avoid key collisions, or to create constants. With TypeScript, you can use Symbols with type checking and code completion, making them even more useful in large-scale applications.