以下代码
class MakeIterable {
index: number;
data: number[];
constructor(data: number[]) {
this.index = 0;
this.data = data;
}
[Symbol.iterator]() {
return {
next: () => {
if (this.index < this.data.length) {
return {
value: this.data[this.index++],
done: false
};
} else {
this.index = 0; //If we would like to iterate over this again without forcing manual update of the index
return {done: true};
}
}
}
};
}
const itrble: MakeIterable = new MakeIterable([1,2,3,4,5]);
for (const val of itrble) {
console.log(val); // expecting '1' '2' '3' '4' '5'
}
给定配置,
{
"compilerOptions": {
"lib": ["es2015", "dom"]
},
"files": [
"tstut.ts"
]
}
如何解决以下错误?
$ tsc --target ES5
tstut.ts(30,19): error TS2495: Type 'MakeIterable' is not an array type or a string type
$ tsc --target ES6
tstut.ts(30,19): error TS2322: Type 'MakeIterable' is not assignable to type 'Iterable<number>'.
Types of property '[Symbol.iterator]' are incompatible.
Type '() => { next: () => { value: number; done: boolean; } | { done: boolean; value?: undefined; }; }' is not assignable to type '() => Iterator<number>'.
Type '{ next: () => { value: number; done: boolean; } | { done: boolean; value?: undefined; }; }' is not assignable to type 'Iterator<number>'.
Types of property 'next' are incompatible.
Type '() => { value: number; done: boolean; } | { done: boolean; value?: undefined; }' is not assignable to type '(value?: any) => IteratorResult<number>'.
Type '{ value: number; done: boolean; } | { done: boolean; value?: undefined; }' is not assignable to type 'IteratorResult<number>'.
Type '{ done: boolean; value?: undefined; }' is not assignable to type 'IteratorResult<number>'.
Property 'value' is optional in type '{ done: boolean; value?: undefined; }' but required in type 'IteratorResult<number>'.