Answer the question
In order to leave comments, you need to log in
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
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>;
}
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 questionAsk a Question
731 491 924 answers to any question