YouTip LogoYouTip

Ts Symbol

Symbol is a primitive data type introduced in ES6, representing a unique identifier. In TypeScript, Symbol can be used as object property keys to ensure property uniqueness. This is very useful in scenarios requiring private property creation, avoiding property name conflicts, etc. * * * * * * ## Why Need Symbol In JavaScript, object property names are all strings, which can sometimes lead to conflicts. Symbol provides a way to create unique identifiers, and each call to Symbol() creates a new, unique value. This is very useful in scenarios requiring private property creation, defining unique constants, implementing iterators, etc. > **Concept Explanation:** Symbol is one of JavaScript's primitive data types, created through the Symbol() function. Each Symbol value is unique, even if the descriptions are the same they are not equal. * * * ## Create Symbol Use the Symbol() function to create unique Symbol values. ## Example // Create Symbol, pass description string (optional) var sym1 = Symbol("description"); var sym2 = Symbol("description"); // Each created Symbol is unique, even with the same description console.log("sym1 === sym2: "+(sym1 === sym2)); console.log("sym1: "+ sym1.toString()); **Run Result:** sym1 === sym2: false sym1: Symbol(description) > **Uniqueness:** This is the most important characteristic of Symbol. Each call to Symbol() creates a new value that is not equal to any other value. * * * ## Symbol as Object Property Symbol can be used as object property keys to create unique property names. ## Example // Create Symbol as property key var sym = Symbol("key"); // Use Symbol as object property key var obj ={ name:"Alice",// Regular string property :"secret value"// Symbol property, computed property name }; // Access regular property console.log("Regular property: "+ obj.name); // Access Symbol property console.log("Symbol property: "+ obj); // Symbol properties do not appear in JSON console.log("Object: "+ JSON.stringify(obj)); **Run Result:** Regular property: AliceSymbol property: secret value Object: {"name":"Alice"} > **Privacy:** Symbol properties do not appear in JSON serialization, nor are they enumerated in for...in loops. 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 // Use Symbol.for method to create/get global Symbol // If key doesn't exist, create new; if exists, return existing var globalSym1 = Symbol.for("global"); var globalSym2 = Symbol.for("global"); // Symbols with the same key are equal console.log("Global Symbol equal: "+(globalSym1 === globalSym2)); // Get Symbol's key console.log("Symbol key: "+ Symbol.keyFor(globalSym1)); **Run Result:** Global Symbol equal: trueSymbol key: global > **Difference:** Symbol() creates new values each time, Symbol.for() looks up or creates in the global registry. * * * ## Built-in Symbols JavaScript defines some built-in Symbol values for customizing language behavior. ## Example // Symbol.iterator is used to define default iterator for objects var arr =[1,2,3]; // Get iterator for array var iterator = arr[Symbol.iterator](); // Use iterator to traverse console.log("First element: "+ iterator.next().value); console.log("Second element: "+ iterator.next().value); // Symbol.toStringTag customizes object's toString() return value var obj ={ [Symbol.toStringTag]:"MyObject" }; console.log("Object type: "+ obj.toString()); **Run Result:** First element: 1Second element: 2Object type: > **Important:** Built-in Symbols are used to customize language behavior, such as iterators, type conversion, etc. They are the foundation of JavaScript advanced features. * * * ## Symbol Type Annotations Use Symbol type for type annotations in TypeScript. ## Example // Symbol type annotation var sym: symbol = Symbol("key"); // Object key type is symbol, value is string var obj:{[key: symbol]: string }={}; // Use Symbol as key obj="value"; console.log("Symbol property value: "+ obj); > **Type:** Use `symbol` type annotation for Symbol values in TypeScript. * * * ## Notes * **Uniqueness:** Each Symbol() call creates a different value * **Non-enumerable:** Symbol properties do not appear in for...in loops * **JSON ignore:** Symbol properties are not serialized by JSON * **Global registry:** Symbol.for() shares in global registry > **Application Scenarios:** Symbol is commonly used for creating private properties in objects, defining unique constants, avoiding property name conflicts, etc. * * * ## Summary Symbol is an important primitive type in TypeScript. * **Uniqueness:** Each created Symbol is not equal to others * **Property keys:** Can be used as unique property keys for objects * **Global registry:** Symbol.for() creates/gets global Symbols * **Built-in Symbols:** Symbol.iterator, Symbol.toStringTag, etc. * **Type annotations:** Use symbol type > **Suggestion:** Use Symbol when you need to create unique identifiers, avoid property name conflicts, or need "private" properties.
← Ts Set WeakmapTs Assertion β†’