Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite the simple iterable class from JavaScript to TypeScript?

I wrote the simple iterable class on JavaScript ES6:

// JavaScript ES6
class FooIterable {
	
	constructor(items){
		this.data = items; 
	}
	
	*[Symbol.iterator](){
		for(let n of this.data){
			yield n;
		}
	}
}

const foo = new FooIterable(['Bob','John','Mark']);

for(let n of foo) console.log(n);

Now I want to write the same on TypeScript 2.6. This is my attempt:

class FooIterable {

    data: string[];

    constructor(items : string[]){
        this.data = items; 
    }

    *[Symbol.iterator](){
        for(let n of this.data){
            yield n;
        }
    }
}
const foo = new FooIterable(['Bob', 'John', 'Mark']);
for(let n of foo) console.log(n);

But I see such error in the online editor:

enter image description here

How can I do what I need?

like image 392
Andrey Bushman Avatar asked Dec 21 '25 10:12

Andrey Bushman


1 Answers

Using iterators requires the downlevelIteration compiler option. I don't see where this option is exposed in the playground, unfortunately.

As an alternative, you could use Array.from since that will convert it to an array type that can be used, and .from will use the iterator internally as well.

for (let n of Array.from(foo))

NOTE: for an target that supports this iteration natively (such as es6) you don't need the downlevelIteration option.

like image 139
Explosion Pills Avatar answered Dec 24 '25 00:12

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!