当我尝试迭代从 Map.values()
返回的值时,Typescript 给了我这个错误(其中 Map 的类型为
error TS2495: Type 'IterableIterator<Foo>' is not an array type or a string type.
根据 ES6 doc Map.values()
应该返回一个 Iterable
而不是 IterableIterator,我应该能够在 for-of 循环中使用它。
这在 node
中工作正常:
var data = [
{id: 0},
{id: 1},
{id: 3}
];
var m = new Map(data.map(n => [n.id,n]));
for(var i of m.values()) { console.log(i) }
这给出了来自 tsc
的错误:
interface Foo {
id: number;
}
var data: Foo[] = [
{id: 0},
{id: 1},
{id: 2}
];
var m = new Map<number,Foo>(data.map(n => <[number,Foo]>[n.id,n]));
for(var i of m.values()) { console.log(i) }
我从 @types/core-js@0.9.34
得到 Map 声明,所以我猜问题出在这个声明中??
其他版本和配置信息:
> tsc --version
Version 2.0.3
> cat tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"typeRoots": [
"./node_modules/@types/"
]
},
"compileOnSave": true,
"exclude": [
"node_modules/*",
"**/*-aot.ts"
]
}
最佳答案
我不理解 tsc
正在对 tsconfig.json
做一些隐含的事情。读书tsconfig.json doc让事情更清楚:
首先,我像这样转译 tsc mytypescript.ts
这(愚蠢地)导致 Typescript 静默忽略 tsconfig.json 文件,这意味着它使用默认的 ES5 .但这部分起作用了,因为 tsc
仍在寻找 core-js
声明,其中包含 ES6 声明,如 Map、Iterable 等。这让我的调试有点困难。
其次,在让 Typescript 实际获取我的配置后,无论如何配置都是错误的。我实际上不需要或不想要来自 @types/core-js
的那些声明(很确定)。是的,我将在我的项目中使用 core-js 作为 polyfill,但是 Typescript comes with it's own typescript/lib/lib.es6.d.ts
中的 ES6 声明,以及 @types/core-js
中的声明是古老的怪异和糟糕的东西.. .
关于javascript - Typescript 错误 : Map. values() 给出 IterableIterator not Iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798918/