实现 Iterator<T> 的 Typescript 接口

Typescript Interfaces implementing Iterator<T>

我正在尝试了解这是否可能...

export interface ISomething { ... }
export interface ISomethingElse implements Iterator<ISomething> { ... doSomeJob(): void; ... }

我的想法是,当我声明我的 class、ClassA 时,我可以做这样的事情...

export ClassA implements ISomethingElse { 

public doSomeJob(): void {
    for (let item of this) {
        console.log(item);
    }
}

}

我希望在 C# 中实现类似于此声明的功能

public interface ISomethingElse : IEnumerable<ISomething> {
    void DoSomeJob();
}

我认为您正在寻找 extends 寻找 interfaces

摘录:

扩展接口

Like classes, interfaces can extend each other. This allows you to copy the members of one interface into another, which gives you more flexibility in how you separate your interfaces into reusable components.

interface Shape {
  color: string;
} 

interface Square extends Shape {
  sideLength: number;
}   

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;

如果你想使用Iterator那么你可以这样做:

interface ISomething { }

interface ISomethingElse extends Iterator<ISomething> {
    doSomeJob(): void;
}

class ClassA implements ISomethingElse {
    private counter: number = 0;

    public next(): IteratorResult<ISomething>{
        if (++this.counter < 10) {
            return {
                done: false,
                value: this.counter
            }
        } else {
            return {
                done: true,
                value: this.counter
            }
        }

    }

    public doSomeJob(): void {
        let current = this.next();
        while (!current.done) {
            console.log(current.value);
            current = this.next();
        }
    }
}

(code in playground)

但是如果你想使用 for/of 循环那么你需要使用 Iterable:

interface ISomethingElse extends Iterable<ISomething> {
    doSomeJob(): void;
}

class ClassA implements ISomethingElse {
    [Symbol.iterator]() {
        let counter = 0;

        return {
            next(): IteratorResult<ISomething> {
                if (++this.counter < 10) {
                    return {
                        done: false,
                        value: counter
                    }
                } else {
                    return {
                        done: true,
                        value: counter
                    }
                }
            }
        }
    }

    public doSomeJob(): void {
        for (let item of this) {
            console.log(item);
        }
    }
}

(code in playground)

但是你需要以 es6 为目标,否则你会在 for/of 循环中遇到错误(就像在 playground 中一样):

Type 'this' is not an array type or a string type

您可以在此处找到更多相关信息:
Iterators and generators
在这里:
Iteration protocols