Search code examples
javascripttypescriptiterator

How do I iterate/access response headers from a fetch call in Typescript?


Consider the following TS example:

fetch("http://localhost:3000/auth", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
    body: JSON.stringify(data)
  })
  .then((response) => {
    // would like to store some information from the response's headers
    // like access tokens etc.

    // Typescript complains about this iteration (see more info below)
    for (var pair of response.headers.entries()) {
      console.log(pair[0] + ': ' + pair[1])
    }

    return response.json()
  })
  // get the response data etc...
  .then((data) => {
    console.log(data);
  })
  // log an error etc...
  .catch((error) => {
    console.log('ERROR: ', error);
  })

Normally, this would be valid but Typescript complains about the iteration and suggests a compiler option:

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

Are there any downsides to using --downlevelIteration? Is there another way of accomplishing this without having to change the compiler options?

Thanks!


Solution

  • Iterators (in some languages called Enumerators) were added in ES6. They are not present in ES5 and older. Before ES6 only iterable construct was Array or so-called array like native objects. ES6 brought iterators and features like for ... of that works with them. When targeting below ES6 you have to use downlevelIteration in order to transpile ES6 iterator code to ES5 compatible code (iterator will be changed do Arrays and for ... of will be replaced by ES5 valid syntax). If you are using no other transpiler beside TSC you have no other choice but enable this flag.