Use case
If you’re using JavaScript Map and want to access its values as an array, you might first think to get its values like Object.values:
const map: Map<string, BlogArticle> = new Map<string, BlogArticle>();
...
// DOES NOT WORK
articles: BlogArticle[] = map.values;
There’s a slight problem
In order to typecast a custom object into an array, the object must implement the iterable protocol and have the Symbol.iterator method. When called without arguments, this method must return an iterator that has the next() method defined.
Until it does, the two objects are totally incompatible. You will see the following error:
Type '() => IterableIterator<BlogArticle>' is not assignable to type 'BlogArticle[]'.
Solution
- Call Map.prototype.values() so that it returns an Iterator object with values
- Use JavaScript’s spread syntax to make a shallow copy
// DOES WORK
articles: BlogArticle[] = [...map.values()];
Leave a Reply