Reputation: 393
I have a TypeScript class List
which is imported. (It acts like a Singly Linked List). I am trying to implement an iterator for the class.
List.prototype[Symbol.iterator] = function* gen() {
...
};
However, TypeScript server says "Element implicitly has an 'any' type because expression of type 'symbol' can't be used to index type 'List'".
What is the proper way of implementing and using an iterator for a TypeScript class?
Upvotes: 2
Views: 544
Reputation: 45222
Here is a simple example of a default iterator on a class:
class List {
*[Symbol.iterator]() {
yield "Foo";
yield "Bar";
}
}
const list = new List();
for (let element of list) {
console.log(`element ${element}`)
}
If the List already exists and you cannot directly add members to it, you can extend it through a prototype. Before you can assign the member to the prototype, you must declare the new member via an interface:
// This is defined elsewhere and cannot be modified
class List {
// ...
}
// This is our code that extends it by adding a default iterator
interface List {
[Symbol.iterator]: () => Iterator<string>;
}
List.prototype[Symbol.iterator] = function* () {
yield "Foo";
yield "Bar";
};
const list = new List();
for (let element of list) {
console.log(`element ${element}`)
}
Upvotes: 2