GoldenFish GoldenFish - 1 month ago 10
TypeScript Question

TypeScript compiler unable to find immutable.js Map iterator in for of loop

I'm trying to use immutable.js with TypeScript but having a hard time convincing the compiler that a

Map
has an iterator. The code works in ES6 so I am not sure why it doesn't work in TypeScript.

Code

import {Map} from "immutable";

const m = Map({ a: 1 });

for (const [key, value] of m) {
console.log(key, value);
}


Expected output:

a 1


Actual:

TSError: тип Unable to compile TypeScript
src/test.ts (6,28): Type must have a '[Symbol.iterator]()' method that returns an iterator. (2488)


ES6 example:

const Immutable = require( "immutable");

const m = Immutable.Map({ a: 1 });

for (const [key, value] of m) {
console.log(key, value);
}


Output:

a 1


Extra notes:

I have also tried
m.entries()
and
m.entrySeq()
all produce the same error.

I am using TypeScript 2.0.3

Answer

It seems that the definition file for immutable.js doesn't include this, but you can add it yourself:

import {Map} from "immutable";

declare module "immutable" {
    interface Map<K, V> {
        [Symbol.iterator](): IterableIterator<[K,V]>;
    }
}

const m = Map({ a: 1 });

for (const [key, value] of m) { // should be fine
    console.log(key, value);
}