What is the unique symbol is used for?
What is the unique symbol is used for?
The unique symbol
in TypeScript is used to create symbols that serve as unique and immutable identifiers for object properties. Symbols are a primitive data type introduced in ECMAScript 2015 (ES6) and are supported in TypeScript to enable unique property keys that do not collide with any other keys in an object, ensuring that the properties are unique even if their descriptions are the same. The unique symbol
type is a subtype of the symbol
type and is produced by calling Symbol()
or Symbol.for()
, or through explicit type annotations.
The primary use of unique symbol
is to enable treating symbols as unique literals, allowing for more precise type checking and ensuring that each symbol is distinct from others, even if they share the same description. This is particularly useful in scenarios where you want to create private or protected identifiers that cannot be easily duplicated or accessed outside of their intended scope.
In TypeScript, unique symbol
types can only be declared with const
or as readonly
static properties. This restriction ensures that the symbols remain immutable and their unique identity is preserved throughout the code. To reference a specific unique symbol
, you must use the typeof
operator, which allows you to refer to the symbol's unique identity rather than just its type.
Here's an example illustrating the use of unique symbol
:
declare const MY_UNIQUE_SYMBOL: unique symbol;
type MyObjectType = {
[MY_UNIQUE_SYMBOL]: string;
};
const myObject: MyObjectType = {
[MY_UNIQUE_SYMBOL]: "UniqueValue",
};
// Accessing the property using the unique symbol
console.log(myObject[...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào