从TypeScript 1.8切换到2.0.3一些实现Iterator的代码已经开始生成一条新消息: 错误TS2322:输入'{done:true; }'不能赋值为'IteratorResult'.类型'{done:true; }". 虽然修复很容易(并且向后兼容),但我想了解它为什么会发生变化......
至少在TypeScript 1.8下,IteratorResult使用value属性optional来定义.从lib.es6.d.ts for 1.8:
interface IteratorResult<T> {
done: boolean;
value?: T;
}
Run Code Online (Sandbox Code Playgroud)
声明如下:
interface IteratorResult<T> {
done: boolean;
value: T;
}
Run Code Online (Sandbox Code Playgroud)
凭借严格的空检查关,供应的{ done: true, value: undefined }解决方法是显而易见的,但在那里一些很好的理由让value强制在2.0吗?
更新:我现在发现,当我打开严格的空检查时,这会变得更糟,显式使用undefined(如上所述)也不起作用.最终我采取了这个:
return { done: true, value: undefined } as any as IteratorResult<T>;
Run Code Online (Sandbox Code Playgroud)
作为参考,这是生成错误的代码示例:
class HashMapKeyIterable<K,V> implements Iterator<K>, IterableIterator<K> {
private _bucket: HashMapEntry<K,V>[];
private _index: number;
constructor( private _buckets : Iterator<HashMapEntry<K,V>[]> ){
this._bucket = undefined;
this._index = undefined;
}
[Symbol.iterator]() { return this }
next(): IteratorResult<K> {
while (true) {
if (this._bucket) {
const i = this._index++;
if (i < this._bucket.length) {
let item = this._bucket[i];
return {done: false, value: item.key}
}
}
this._index = 0
let x = this._buckets.next();
if (x.done) return {done: true}; // Under TS 2.0 this needs to
this._bucket = x.value; // return {done: true: value: undefined};
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:这现在看起来像一个错误,我已经提交了问题11375跟踪.
| 归档时间: |
|
| 查看次数: |
514 次 |
| 最近记录: |