2

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?

1 Answer 1

2

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}`)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the sample code! However, I hadn't previously clarified, class List is imported, and hence, I had to use prototype inheritance. To implement it within the class, I would have to create class NewList extends List. How can I avoid creating new classes?
@acagastya Turns out that it is possible to do what you're asking. I've added the alternative syntax (using a prototype) to the answer.
Without the interface, tsserver was giving an error. The interface fixes the problem! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.