TypeScript 编译器无法在 for of 循环中找到 immutable.js Map 迭代器
TypeScript compiler unable to find immutable.js Map iterator in for of loop
我正在尝试将 immutable.js 与 TypeScript 一起使用,但很难让编译器相信 Map
具有迭代器。该代码在 ES6 中工作,所以我不确定为什么它在 TypeScript 中不起作用。
代码
import {Map} from "immutable";
const m = Map({ a: 1 });
for (const [key, value] of m) {
console.log(key, value);
}
预期输出:
a 1
实际:
TSError: ⨯ Unable to compile TypeScript
src/test.ts (6,28): Type must have a '[Symbol.iterator]()' method that returns an iterator. (2488)
ES6 示例:
const Immutable = require( "immutable");
const m = Immutable.Map({ a: 1 });
for (const [key, value] of m) {
console.log(key, value);
}
输出:
a 1
补充说明:
我也试过 m.entries()
和 m.entrySeq()
都产生同样的错误。
我正在使用 TypeScript 2.0.3
immutable.js
的定义文件好像没有这个,你可以自己添加:
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);
}
我正在尝试将 immutable.js 与 TypeScript 一起使用,但很难让编译器相信 Map
具有迭代器。该代码在 ES6 中工作,所以我不确定为什么它在 TypeScript 中不起作用。
代码
import {Map} from "immutable";
const m = Map({ a: 1 });
for (const [key, value] of m) {
console.log(key, value);
}
预期输出:
a 1
实际:
TSError: ⨯ Unable to compile TypeScript
src/test.ts (6,28): Type must have a '[Symbol.iterator]()' method that returns an iterator. (2488)
ES6 示例:
const Immutable = require( "immutable");
const m = Immutable.Map({ a: 1 });
for (const [key, value] of m) {
console.log(key, value);
}
输出:
a 1
补充说明:
我也试过 m.entries()
和 m.entrySeq()
都产生同样的错误。
我正在使用 TypeScript 2.0.3
immutable.js
的定义文件好像没有这个,你可以自己添加:
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);
}