C
C
copal2016-04-12 11:36:59
JavaScript
copal, 2016-04-12 11:36:59

How to create a typed iterator?

What is the correct way to create a typed iterator?

class Node {
    public id: number;

    constructor(id: number){
        this.id = id;
    }
}

class List {
    public nodeAll: Node[];

    constructor(nodeAll: Node[]){
        this.nodeAll = nodeAll;
    }

    iterator(): Iterator<Node> {
        return this.nodeAll[Symbol.iterator]();
    }
}

let list = new List([new Node(0), new Node(1), new Node(2)]);

let iterator: Iterator<Node> = list.iterator();

for(let node of iterator){
    console.log(node.id);
}

error TS2488: Type must have a '[Symbol.iterator]()' method that returns an iterator.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-04-12
@copal

I'm not sure, but it seems to me that typescript is waiting for an IterableIterator interface

interface IterableIterator<T> extends Iterator<T> {
    [Symbol.iterator](): IterableIterator<T>;
}

Try like this
class Node {
    public id: number;

    constructor(id: number){
        this.id = id;
    }
}

class List {
    public nodeAll: Node[];

    constructor(nodeAll: Node[]){
        this.nodeAll = nodeAll;
    }

    iterator(): IterableIterator<Node> {
        return this.nodeAll[Symbol.iterator]();
    }
}

let list = new List([new Node(0), new Node(1), new Node(2)]);

let iterator: IterableIterator<Node> = list.iterator();

for(let node of iterator){
    console.log(node.id);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question