*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();
Symbols can be used as property keys in objects, using square bracket notation.
const myObject = { };
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'
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'
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.