TS1163: Typescript wont allow yield within functions

54 Views Asked by At

I know it doesn't allow this, but why? Feels like an unnecessary limitation of the language / compiler...

Something as simple as this wont work:

*(array:number[]){
    array.forEach(i => yield i+1)
}

Of course this could be replaced with a for loop:

*(array:number[]){
    for (const i of array)
        yield i + 1
    }

But a more practical example might be:

async*(){
    await pollX(async () => {
        const x = getX();
        for (const value of x.values)
            yield value
        return x.stop
    })

Now it's not a simple - or even possible - refactor (without changing the underlying pollX function to be an async-generator itself (which I may not have control over)


It seems like the JS engine could obviously restructure the code for me - just like it does with async-await => promises

Similarly, before async await, some code became an utter mess of nested promise callbacks; here, you can get into an utter mess of yield hacking (that would be easily solved if the engine just implemented the restructuring).

So far, none of the answers really answer the question - ultimately, it seems possible, but maybe was not a priority for the engine developers? Or is it just not possible (this is my question).

0

There are 0 best solutions below