eclipse / n4js

Eclipse Public License 1.0
30 stars 24 forks source link

Incorrect signature of method #next() in built-in type Generator #1983

Open mor-n4 opened 3 years ago

mor-n4 commented 3 years ago

Method Generator#next() is declared as

public abstract next(value: TNext = undefined): IteratorEntry<TYield>

but this seems to be incorrect, because the value in the IteratorEntry returned by #next() might be the generator's return value.

To reproduce:

function* gen(): Generator<string,number,?> {
    yield 'hello';
    return 42;
}
const g = gen();
g.next();
const str: string = g.next().value;
str.toUpperCase(); // TypeError: str.toUpperCase is not a function

Probably the signature should be:

public abstract next(value: TNext = undefined): IteratorEntry<TYield | TReturn>
mmews-n4 commented 3 years ago

Mind the example below copied from 2ality.com.

Code

function* genFuncWithReturn() {
    yield 'a';
    yield 'b';
    return 'result';
}

Output

> let genObjWithReturn = genFuncWithReturn();
> genObjWithReturn.next()
{ value: 'a', done: false }
> genObjWithReturn.next()
{ value: 'b', done: false }
> genObjWithReturn.next()
{ value: 'result', done: true }

Mind that loops etc. ignore the last entry (done == true).

for (let x of genFuncWithReturn()) {
    console.log(x);
}
// Output:
// a
// b

let arr = [...genFuncWithReturn()]; // ['a', 'b']