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 private object properties, 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 a Symbol as a key for object properties

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.

Creating private object properties with Symbols

Another common use case for Symbols is to create private object properties. Because Symbols are unique and cannot be accessed by other parts of the code, they can be used to define properties that are hidden from other parts of the application.

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

In this example, mySymbol is used to define a private property for the MyClass class. The property is initialized with the value “private value”. The getPrivateValue() method is used to return the private property value. Because mySymbol is unique and cannot be accessed from outside the class, the private property is hidden from other parts of the application.

Conclusion

Symbols are a powerful and useful addition to the JavaScript language. They provide a way to create unique and immutable values that can be used as keys for object properties, to define private object properties, 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.