How to typecast an IterableIterator into an Array using JavaScript

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

  1. Call Map.prototype.values() so that it returns an Iterator object with values
  2. Use JavaScript’s spread syntax to make a shallow copy
// DOES WORK
articles: BlogArticle[] = [...map.values()];

Discover more from Cloud Engineering Studio

Subscribe to get the latest posts sent to your email.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *