我的界面定义了迭代器:
[Symbol.iterator]() : IterableIterator<IDocument>;
我的班级DocumentManager
实现了这个界面:
*[Symbol.iterator](): IterableIterator<IDocument>{
for(let n of this._documents){// this._documents is Array<IDocument>
yield n;
}
}
在调试模式下,我看到this._documents
有三个文档,但是这段代码没有迭代:
let m = 0;
for(let n of app.documentManager){
++m;
}
// here m == 0 still...
所以迭代不会发生。我做错了什么?
UPD
例如,它适用于JavaScript:
let collection = {
items : ['a','b','c','d','e'],
*[Symbol.iterator](){
for(let item of this.items){
yield item;
}
}
};
for(let n of collection){
console.log(n);
}
为什么我遇到TypeScript问题?
UPD2
哦,现在我发现它不仅适用于单元测试(Karma
+ Jasmine
),但在Node.js
中工作正常。但我也需要我的单元测试....:((
答案 0 :(得分:0)
我不确定你做错了什么,但这里有一些编译和运行良好的打字稿代码:
interface IterateNum {
[Symbol.iterator](): IterableIterator<number>;
}
class Collection implements IterateNum {
private items = [1,2,3,4]; // can be Array<T>
constructor() {}
*[Symbol.iterator]() {
for(let i of this.items) {
yield i;
}
}
}
for(let n of (new Collection())) {
console.log(n);
}
我编写了上述代码,并复制了您的tsconfig.json
并正在运行tsc
和node dist/file.js
正常工作。您的代码可能还有其他问题。尝试编写一个最小的独立脚本,以获得您感兴趣的部分协同工作,并隔离呼叫站点。
关于此功能集的注释:
您需要实现接口(next
函数),而不仅仅是屈服值。 This online gitbook does a good job on how to implement an interator in TS
Here's a related PR that describes more details of the TS implementation
for-of
低级发射有一些奇怪,所以请确保你的tsconfig设置正确。 (target es6, as per this issue)
注意 - 值得一提的是this other SO answer,问题略有不同,但链接的答案明确谈到了一个看起来更像这个OP正在寻找的Iterable版本。