TypeScript tutorial: Lesson 25 – WeakMap


Starting with ECMAScript 2015, The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

Create a WeakMap:

var myWeakMap = new WeakMap()

Setting object properties

Keys of WeakMaps are of the type Object only.

Use set(key, value) method:

const o1 = {a:1},
      o2 = function() {},
      o3 = {};

myWeakMap.set(o1, 11);
myWeakMap.set(o2, 'hello');
myWeakMap.set(o3, o2); // a value can be anything, including an object or a function

Getting object properties

Use get(key) method:

console.log(myWeakMap.get(o1)) //11
console.log(myWeakMap.get(o2)) //hello
console.log(myWeakMap.get(o3)) //[Function: o2]

Delete an object property

Use delete(key) method:

console.log(myWeakMap.delete(o3)) //true

Size of WeakMap

console.log(WeakMap.size) //2

Instance methods

WeakMap.prototype.delete(key)
Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.
WeakMap.prototype.get(key)
Returns the value associated to the key, or undefined if there is none.
WeakMap.prototype.has(key)
Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
WeakMap.prototype.set(key, value)
Sets the value for the key in the WeakMap object. Returns the WeakMap object.

Leave a Reply