Câu hỏi phỏng vấn Typescript
Câu hỏi

What is the unique symbol is used for?

Câu trả lời

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:

typescript Copy
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

middle

Gợi ý câu hỏi phỏng vấn

junior

How to make Arrays that can only be read, TypeScript?

junior

Which access modifiers are implied when not specified?

entry

List the built-in types in Typescript

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào