5

Switching from TypeScript 1.8 to 2.0.3 some code implementing an Iterator has started generating a new message: error TS2322: Type '{ done: true; }' is not assignable to type 'IteratorResult'. Property 'value' is missing in type '{ done: true; }'. While a fix is easy (and backwards compatible) I'd like to understand why it has changed...

At least under TypeScript 1.8, IteratorResult was defined with the value property optional. From lib.es6.d.ts for 1.8:

interface IteratorResult<T> {
    done: boolean;
    value?: T;
}

Under 2.0 the declaration reads:

interface IteratorResult<T> {
    done: boolean;
    value: T;
}

With strict null checking off, the of supplying { done: true, value: undefined } fix is obvious but was there some good reason to make value mandatory in 2.0?

UPDATE: I've now discovered that when I turn on strict null checking, this gets worse, explicitly using undefined (as above) doesn't work either. Eventually I resorted to this:

return { done: true, value: undefined } as any as IteratorResult<T>;

For reference, here's an example of the code generating the error:

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};
            }
        }
    }

Update: This now seems like a bug, I've filed issue 11375 to track.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.