Explain the symbol type in TypeScript
In Typescript symbol is a primitive data type. A primitive data type is not an object, it possesses no properties or methods and they cannot be altered. The symbol type is similar to other types such as number, string, boolean, etc. Symbol values are created using the Symbol constructor.
Syntax: Following is the syntax to create a symbol value:
Symbol() // OR Symbol("string")
Example 1: Creating symbols
Symbols are created using the symbol constructor directly or by using an optional key in addition. We created a normal symbol and a symbol with an optional key “abc”.
Example 2: Every symbol is unique
Every symbol is unique. The below code checks if two symbols are the same but false is returned as we compare two symbols.
Example 3: Symbols as keys for object properties
As symbols are unique they can be used as keys for object properties.
Example4: Symbols used to declare class members or class methods
In this example, a class member is declared by using symbols. The method returns the name of the class. We call the class by creating an object and then access the method.
Example 5: Symbols as unique literals
Generally, symbols are only treated as a type. To treat symbols as unique literals, typescript has a special type called ‘unique symbol’. It is a subtype of Symbol(). The ‘unique symbol’ can be used only with those variables which are declared const or on read-only properties. If we want to reference a unique symbol type variable we need to use the type of operator.
'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later.
Unique type variable must be const. The right declaration is shown below:
declare const symbol1: unique symbol;
Please Login to comment...