React, TypeScript

TypeScript – URLSearchParams iterator typing issue

In a certain React course in Udemy, I encountered an issue on React and Typescript where an iterator does not work the way it is shown in the course and this is probably because the course is not written in TypeScript, but in plain JavaScript.

Here is the original code:

const query = new URLSearchParams(this.props.location.search);
let ingredients:any = {};

for (let param of query.entries()) {
  ingredients[param[0]] = param[1];
}

The compiler complaints about the typing and I got this error:

Type 'IterableIterator<[string, string]>' is not an array type or a string type.
Use compiler option '--downlevelIteration' to allow iterating of iterators

Instead of messing around with types, I got a workaround which is to use a different iteration method, the forEach method. Below is the new code and it works without compiler errors.

const query = new URLSearchParams(this.props.location.search);
let ingredients:any = {};

query.forEach((v, k) => {
  ingredients[k] = v;
});

I almost swapped the key and value parameters but of course I figured it out pretty quickly.

That’s it! Simple issues with simple solutions.

No Comments

Leave a reply

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