khusamov
@khusamov
ReactJS, NodeJS, TypeScript, Sencha ExtJS

Как написать правильный итератор на Typescript?

Я написал следующее (взяв за основу 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));


но получил такие ошибки


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.
  • Вопрос задан
  • 106 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы