gpt4 book ai didi

TypeScript:[Symbol.iterator] 的实现:为什么它在单元测试中不起作用(Karma + Jasmine?

转载 作者:行者123 更新时间:2023-12-04 02:01:19 25 4
gpt4 key购买 nike

我的接口(interface)定义了迭代器:

[Symbol.iterator]() : IterableIterator<IDocument>;

我的类(class) DocumentManager实现这个接口(interface):
*[Symbol.iterator](): IterableIterator<IDocument>{
for(let n of this._documents){// this._documents is Array<IDocument>
yield n;
}
}

在 Debug模式下,我看到 this._documents有三个文档,但这段代码不会迭代:
let m = 0;
for(let n of app.documentManager){
++m;
}
// here m == 0 still...

所以迭代不会发生。我做错了什么?

更新

例如,它适用于 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 中可以正常工作.但我也需要我的单元测试工作...... :(((

最佳答案

我不确定你做错了什么,但这里有一些可以编译和运行良好的 typescript 代码:

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并运行 tscnode dist/file.js工作正常。您的代码可能还有其他问题。尝试编写一个最小的独立脚本,让您感兴趣的部分协同工作,并隔离调用站点。

关于此功能集的一般注意事项:

您需要实现接口(interface)( 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 版本。

关于TypeScript:[Symbol.iterator] 的实现:为什么它在单元测试中不起作用(Karma + Jasmine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com