S
S
Svyatoslav Khusamov2017-04-06 16:14:18
typescript
Svyatoslav Khusamov, 2017-04-06 16:14:18

How to write a proper iterator in Typescript?

I wrote the following (based on learn.javascript.ru/iterator ):

class MyRange {
    
    from: number;
    
    to: number;
    
    current: number;
    
    constructor(from: number, to: number) {
        this.from = from;
        this.to = to;
    }
    
    [Symbol.iterator]() {
        return this;
    }
    
    next() {
        if (this.current === undefined) {
            this.current = this.from;
        }
        if (this.current <= this.to) {
            return {
                done: false,
                value: this.current++
            };
        } else {
            this.current = undefined;
            return {
                done: true
            };
        }
    }
    
}

let range = new MyRange(0, 10);
console.log('Перебор итератора:');
for (let i of range) {
    console.log(i);
}
console.log('Поиск максимального значения:');
console.log(Math.max(...range));

but got these errors

temp.ts(40,15): error TS2495: Type 'MyRange' is not an array type or a string type.
temp.ts(44,25): error TS2461: Type 'MyRange' is not an array type.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question