YouTip LogoYouTip

Ts Set Weakmap

TypeScript inherits Set and WeakMap data structures from JavaScript, providing more powerful type support. These data structures are very useful for handling unique value sets, key-value mappings, caching, and other scenarios. * * * * * * ## Why Set and WeakMap Are Needed In development, we often need to handle unique value sets and key-value mappings. Set provides automatic deduplication functionality for collections, making it more convenient than arrays for handling unique values. WeakSet and WeakMap use weak references and do not prevent garbage collection, suitable for scenarios where memory leaks need to be avoided, such as caching DOM nodes. > **Concept Explanation:** Set is a collection of values, with unique values; Map is a collection of key-value pairs, where keys can be of any type. WeakSet and WeakMap use weak references that do not affect garbage collection. * * * ## Set Set is a collection of values, with unique values, no duplicates allowed. ## Example // Create a Set, specify element type as number var numbers =new Set(); // Add elements numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(1);// Duplicate values are ignored and not added // Check size and inclusion console.log("Set size: "+ numbers.size); console.log("Contains 2: "+ numbers.has(2)); // Iterate over Set numbers.forEach(function(value){ console.log("Value: "+ value); }); // Convert to array var arr =Array.from(numbers); console.log("Converted to array: "+ arr); **Output:** Set size: 3Contains 2: trueValue: 1Value: 2Value: 3Converted to array: 1,2,3 > **Deduplication:** Set automatically ignores duplicate values, making it ideal for array deduplication. * * * ## Set Type Annotation You can explicitly specify the type of values in a Set. ## Example // String Set // Can only add string values var stringSet: Set=new Set(); stringSet.add("a"); stringSet.add("b"); // Object Set // Define Person interface interface Person { name: string; } // Create Set storing Person objects var personSet: Set=new Set(); personSet.add({ name:"Alice"}); personSet.add({ name:"Bob"}); console.log("String Set: "+Array.from(stringSet)); console.log("Object Set size: "+ personSet.size); > **Generics:** Use `Set` syntax to specify the type of elements in the Set. * * * ## WeakSet WeakSet stores object references, with weak references (not affecting garbage collection). ## Example // WeakSet can only store objects, not primitive values var weakSet =new WeakSet(); // Create objects var obj1 ={ name:"Alice"}; var obj2 ={ name:"Bob"}; // Add objects to WeakSet weakSet.add(obj1); weakSet.add(obj2); // Check if contains console.log("Contains obj1: "+ weakSet.has(obj1)); // After removing reference, the object may be garbage collected weakSet.delete(obj1); console.log("Contains obj1 after deletion: "+ weakSet.has(obj1)); > **Note:** WeakSet cannot be iterated, and type annotations can only be `object`. This makes WeakSet suitable for storing objects that should be garbage collected. * * * ## Map Map is a collection of key-value pairs, with keys being of any type. ## Example // Create Map, key type is string, value type is number var map =new Map(); // Set key-value pairs map.set("one",1); map.set("two",2); map.set("three",3); // Get value console.log("Get two: "+ map.get("two")); console.log("Map size: "+ map.size); console.log("Contains three: "+ map.has("three")); // Iterate over Map map.forEach(function(value, key){ console.log(key +": "+ value); }); // Convert to array console.log("Converted to array: "+Array.from(map.entries())); **Output:** Get two: 2Map size: 3Contains three: true one: 1 two: 2 three: 3Converted to array: one,1,two,2,three,3 > **Advantage:** Keys in Map can be of any type (objects, functions, etc.), which is more flexible than using objects as keys. * * * ## WeakMap WeakMap's keys are weak references, not affecting garbage collection. ## Example // Keys in WeakMap must be objects // Key type is object, value type is string var weakMap =new WeakMap(); // Create object as key var keyObj ={ id:1}; // Set key-value pair weakMap.set(keyObj,"value1"); // Get value console.log("Get value: "+ weakMap.get(keyObj)); console.log("Contains: "+ weakMap.has(keyObj)); // Delete key-value pair weakMap.delete(keyObj); console.log("After deletion: "+ weakMap.has(keyObj)); > **Use Case:** WeakMap is commonly used for caching DOM node data. When DOM nodes are removed, cached data is also automatically cleaned up, preventing memory leaks. * * * ## Practical Use Cases Using Map to count occurrences of array elements. ## Example // Use Map to count occurrences of each element in an array function countElements(arr: string[]): Map{ // Create Map, key is string, value is number var counts =new Map(); // Iterate through array for(var _i =0, arr_1 = arr; _i **Practical:** Map is an ideal choice for implementing caches, statistics, indexing, and other functionalities. * * * ## Notes * **Set Uniqueness:** Set automatically ignores duplicate values. * **WeakSet/WeakMap:** Keys must be objects, cannot be iterated. * **Map Key Types:** Keys in Map can be of any type. * **Memory Management:** WeakSet/WeakMap do not prevent garbage collection. > **Recommendation:** Use Set for unique value collections, Map for key-value mapping, and WeakSet/WeakMap to avoid memory leaks. * * * ## Summary Set and Map are very useful data structures in TypeScript. * **Set:** Collection of values, unique values, automatic deduplication. * **WeakSet:** Collection of weak object references, not iterable, suitable for objects that should be garbage collected. * **Map:** Collection of key-value pairs, keys can be of any type. * **WeakMap:** Key is weak reference, not iterable, suitable for caching and private data. > **Suggestion:** Choose the appropriate data structure based on specific needs: use Set for deduplication, Map for mapping, and Weak versions for memory optimization.
← Ts Arrow FunctionTs Symbol β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.