DEV Community

Cover image for Introduction to Symbols Using Type Script
Mahmoud Awd
Mahmoud Awd

Posted on

Introduction to Symbols Using Type Script

*Introduction to Symbols Using Type Script *

Symbols are a unique data type in TypeScript that allows for the creation of unambiguous and immutable values. Unlike other primitive data types such as strings, numbers, and booleans, symbols are not coercible and cannot be converted to other types. They are often used to create private members of classes and to define constants that cannot be changed.

Creating a symbol in Type Script is simple, using the Symbol() function. The function takes an optional string parameter that serves as a description of the symbol, but this parameter has no impact on the value of the symbol itself.

const mySymbol = Symbol();

Enter fullscreen mode Exit fullscreen mode

Symbols can be used as property keys in objects, using square bracket notation.

const myObject = {

};

Enter fullscreen mode Exit fullscreen mode

This allows for the creation of private members in classes, as symbols cannot be accessed from outside the class.

class MyClass {
  private [mySymbol] = 'secret';

  public getSecret(): string {
    return this[mySymbol];
  }
}

const myClassInstance = new MyClass();

console.log(myClassInstance.getSecret()); // 'secret'
console.log(myClassInstance[mySymbol]); // ERROR: Property 'Symbol()' does not exist on type 'MyClass'

Enter fullscreen mode Exit fullscreen mode

Symbols can also be used to define constants, to ensure that the value cannot be changed or overwritten.

const MY_CONSTANT = Symbol();

function myFunction(input: symbol) {
  if (input === MY_CONSTANT) {
    console.log('This is my constant');
  } else {
    console.log('This is not my constant');
  }
}

myFunction(MY_CONSTANT); // 'This is my constant'
myFunction(Symbol()); // 'This is not my constant'

Enter fullscreen mode Exit fullscreen mode

In conclusion, symbols are a powerful feature of TypeScript that can be used to create unambiguous and immutable values, and to define private members and constants. They are particularly useful in object-oriented programming, where they can be used to ensure encapsulation and protect sensitive data.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Symbols are a feature of JS, not TS