我在 TypeScript 中有以下两个类。
class BaseIter {
constructor(public a: number, public b: number, public c: number, public d: number){}
*[Symbol.iterator](): Iterator<number> {
yield this.a
yield this.b
yield this.c
yield this.d
}
}
class MyIter extends BaseIter {
get total() {
return this.a + this.b + this.c + this.d
}
*[Symbol.iterator](): Iterator<number> {
for(let x of this){
yield x
}
yield this.total
}
}
const myIter = new MyIter(1, 2, 3, 4);
for (let n of myIter){
console.log(n);
}
BaseIter
类接受四个参数,并在迭代时返回这四个参数。我有一个扩展 BaseIter
的子类,它应该使用父迭代函数,但也会产生一个额外的值(总计)。当前代码不起作用 - 它会导致无限递归(遍历 this
调用相同的函数,而不是基本函数)。我已经尝试了各种 super
的方法,但没有成功。
我希望它产生
1
2
3
4
10
有什么想法吗?
最佳答案
生成器函数的返回类型为 IterableIterator<T>
, 不是 Iterator<T>
.这阻止了 TypeScript 将父类(super class)中的方法作为可迭代对象使用。通常,您应该让 TypeScript 推断您的函数的返回值,除非它警告您它不能这样做。
class BaseIter {
constructor(public a: number, public b: number, public c: number, public d: number) {}
* [Symbol.iterator] () {
yield this.a;
yield this.b;
yield this.c;
yield this.d;
}
}
class MyIter extends BaseIter {
get total () {
return this.a + this.b + this.c + this.d;
}
* [Symbol.iterator] () {
yield * super[Symbol.iterator]();
yield this.total;
}
}
const myIter = new MyIter(1, 2, 3, 4);
for (const n of myIter) {
console.log(n);
}
关于node.js - 如何从子类的 Symbol.iterator 中调用父类的 Symbol.iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066610/