我有一个项目,其中包含许多理想情况下会实现 Iterable<T>
的类和/或 Iterator<T>
接口(interface)。但是我似乎找不到这些接口(interface)的标准 TypeScript 定义(例如在 typescript-collections 或一些类似的包中)。
我知道这些在 ECMAScript 6 中通过 Symbol.iterator
有所标准化。机制,但我的目标是 ECMAScript 5,并且在可预见的 future 将保持不变。
我能否以某种方式获得这些接口(interface)而无需自己定义它们(例如,为了将来与其他模块的兼容性)?
这是一个副本:typescript: make class objects iterable ,但这是对 ES5
的回答:
您想使用 ES6
feature :
One addition of ECMAScript 2015 (ES6) is not new syntax or a new
built-in, but a protocol. This protocol can be implemented by any
object respecting some conventions.
There are two protocols: The iterable protocol and the iterator
protocol.
在 ES5
环境(编译和/或运行时)中,这不是你能做的。
话虽这么说,你可以足够接近because :
An object is an iterator when it knows how to access items from a
collection one at a time, while keeping track of its current position
within that sequence. In JavaScript an iterator is an object that
provides a next() method which returns the next item in the sequence.
This method returns an object with two properties: done and value.
所以你可以只返回一个带有 next
方法的对象,它是一个迭代器:
class Counter /* implements Iterator<number> */ {
private counter = 0;
//public next(): IteratorResult<number> {
public next(): { done: boolean, value: number } {
return {
done: false,
value: this.counter++
}
}
}
let c = new Counter();
console.log(c.next().value); // 0
console.log(c.next().value); // 1
console.log(c.next().value); // 2
( code in playground )
注释掉的部分将与目标 ES6
一起工作,但低于它时则不行。
但是,如果您的运行时环境确实支持此功能,那么编译后的 js 就可以很好地完成这项工作。