![]() |
In TypeScript, a symbol is a primitive data type. A primitive data type is not an object, possesses no properties or methods, and cannot be altered. The symbol type is similar to other types such as number, string, and boolean. Symbol values are created using the Symbol constructor. Syntax: Following is the syntax to create a symbol value: Symbol() // OR 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”.
Output: Symbol() 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.
Output: false Example 3: Symbols as keys for object properties As symbols are unique they can be used as keys for object properties.
Output: secret_code Example 4: 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.
Output: SymbolClass 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.
Output: 'Symbol' only refers to a type, but is being used Unique type variable must be const. The right declaration is shown below: declare const symbol1: unique symbol; FAQs – Symbol type in TypeScriptWhat is a symbol in TypeScript?
How do you create a symbol in TypeScript?
Can symbols be used as keys for object properties?
What is the difference between a regular symbol and a unique symbol in TypeScript?
Why are symbols useful in TypeScript?
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |