TypeScript Symbol
Symbol is a primitive data type introduced in ES6, representing a unique identifier.
In TypeScript, Symbol can be used as an object's property key, ensuring the uniqueness of properties.
This is very useful in scenarios such as creating private properties and avoiding property name conflicts.
SVG Diagram: How Symbol Works
Why Do We Need Symbol?
In JavaScript, object property names are all strings, which can sometimes lead to conflicts.
Symbol provides a way to create unique identifiers. Each call to Symbol() creates a new, unique value.
This is very useful in scenarios such as creating private properties, defining unique constants, and implementing iterators.
Concept Explanation:Symbol is one of JavaScript's primitive data types, created via the Symbol() function. Each Symbol value is unique; even if their descriptions are the same, they are not equal.
Creating Symbol
Use the Symbol() function to create a unique Symbol value.
Example
var sym1 = Symbol("description");
var sym2 = Symbol("description");
// Each Symbol created is unique, even if the descriptions are the same
console.log("sym1 === sym2: " + (sym1 === sym2));
console.log("sym1: " + sym1.toString());
Output:
sym1 === sym2: false sym1: Symbol(description)
Uniqueness:This is the most important feature of Symbol. Each call to Symbol() creates a new value that is not equal to any other value.
Symbol as an Object Property
Symbol can be used as an object's property key to create a unique property name.
Example
var sym = Symbol("key");
// Use Symbol as the object's property key
var obj = {
name: "Alice", // Ordinary string property
[sym]: "secret value" // Symbol property, computed property name
};
// Access the ordinary property
console.log("Ordinary property: " + obj.name);
// Access the Symbol property
console.log("Symbol property: " + obj[sym]);
// Symbol properties do not appear in JSON
console.log("Object: " + JSON.stringify(obj));
Output:
普通属性: Alice
Symbol 属性: secret value
对象: {"name":"Alice"}
Privacy:Symbol properties do not appear in JSON serialization, nor are they traversed by for...in, so they can be used to create 'private' properties.
Global Symbol Registry
Use Symbol.for() to access Symbols in the global registry. The same key returns the same Symbol.
Example
// If the key does not exist, a new one is created; if it already exists, the existing one is returned
var globalSym1 = Symbol.for("global");
var globalSym2 = Symbol.for("global");
// Symbols with the same key are equal
console.log("Global Symbols equal: " + (globalSym1 === globalSym2));
// Get the key of the Symbol
console.log("Symbol key: " + Symbol.keyFor(globalSym1));
Output:
全局 Symbol 相等: true Symbol key: global
Difference:Symbol() creates a new value each time, while Symbol.for() looks up or creates in the global registry.
Built-in Symbols
JavaScript defines some built-in Symbol values to customize language behavior.
Example
var arr = [1, 2, 3];
// Get the iterator of an array
var iterator = arr[Symbol.iterator]();
// Traverse using the iterator
console.log("First element: " + iterator.next().value);
console.log("Second element: " + iterator.next().value);
// Symbol.toStringTag customizes the return value of an object's toString()
var obj = {
[Symbol.toStringTag]: "MyObject"
};
console.log("Object type: " + obj.toString());
Output:
第一个元素: 1 第二个元素: 2 Object type: [object MyObject]
Important:Built-in Symbols are used to customize language behavior, such as iterators and type conversions, and are the foundation of JavaScript's advanced features.
Symbol Type Annotation
Use the Symbol type for type annotation in TypeScript.
Example
var sym: symbol = Symbol("key");
// The object's key type is symbol, and its value type is string
var obj: { [key: symbol]: string } = {};
// Use Symbol as a key
obj[sym] = "value";
console.log("Symbol property value: " + obj[sym]);
Type:In TypeScript,
symboltype-annotate Symbol values.
Notes
- Uniqueness:The value of each Symbol() call is different
- Non-enumerable:Symbol properties do not appear in for...in loops
- JSON ignores:Symbol properties are not serialized by JSON
- Global registration:Symbol.for() is shared in the global registry
Use cases:Symbol is often used to create private properties of objects, define unique constants, avoid property name conflicts, etc.
Summary
Symbol is an important primitive type in TypeScript.
- Uniqueness:Each Symbol created is not equal to others
- Property key:Can be used as a unique property key for objects
- Global registration:Symbol.for() creates/retrieves global Symbols
- Built-in Symbols:Symbol.iterator, Symbol.toStringTag, etc.
- Type annotation:Use the symbol type
Other ExtensionsRecommendation:Use Symbol when you need to create unique identifiers, avoid property name conflicts, or need 'private' properties.