gpt4 book ai didi

javascript - TS2322 和 TS2495 - 具有 ES6 和 ES5 目标的迭代器

转载 作者:行者123 更新时间:2023-12-03 01:53:54 28 4
gpt4 key购买 nike

对于下面的代码

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>'.

最佳答案

TS2495: Type 'MakeIterable' is not an array type or a string type

使用非数组迭代器的结果。

for..of 和其他迭代方法由于历史原因将可迭代对象视为数组,这会导致不合规但更简洁的输出。

downlevelIteration option应该能够正确处理非数组可迭代对象。

这对于 ES6 目标来说不是必需的。它应该按预期工作,无需 downlevelIteration

TS2322: Type 'MakeIterable' is not assignable to type 'Iterable'.

next 并不总是返回值,尽管它应该返回值。可能应该是:

      ...
} else {
return {value: undefined, done: true};
}
...

关于javascript - TS2322 和 TS2495 - 具有 ES6 和 ES5 目标的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50316339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com