Courtesy of @bterlson (and his idea in general)
interface Foo<T> extends IterableIterator<T> {
next(valueGivenWhenYieldExpressionIsUsed: number)
}
This type is basically an IterableIterator _except_ that it _restricts_ the types of values a consumer can pass through to next.
function* foo(): Foo<string> {
let x = yield "hello";
console.log(x);
}
let gen = foo();
gen.next(100);
gen.next(200);
Here, calls to next can _only_ accept numbers; however, the yield expressions in the generator are just typed as any.
Since we have an explicit type, we should just figure the type of yield expressions out from that.
I guess in the face of overloads, we could take the union of all the types of the first parameters, subbing in undefined when a parameter isn't there.
Can I ask what's the use case/scenario for this? The only common scenario I know of where next is called with an argument is co-style async runners. In that case types passed to next are not related to each other even within the same iteration. They are only related to the types being yielded (not the other way around).
On the other hand, iterables for use in for..of and Map constructors and the like, they don't have anything passed to next.
This issue is largely to track user feedback on whether this is desired, or to at least point to some conversation about the idea. :smile:
is not this the same as https://github.com/Microsoft/TypeScript/issues/2983 but for generators?
I believe this is indeed a duplicate of #2983, which discusses solving (among others) the problem where:
- All
yieldexpressions are typed asany, as you can see in the example comments below.
https://github.com/Microsoft/TypeScript/issues/2983#issuecomment-230414026
(I don't know what @mhegazy meant by "but for generators", #2983 is all about generators as far as I can tell.)
A (much fancier) version of this might be usable to make accurate type definitions for redux-saga. Currently, everything in redux-saga needs explicit types (and hoping that you wrote the right ones) because the result of all yields is any.
For redux-saga, the interface would also need a way to say what is the expected result of a yield when you yield a specific type, which is necessary for coroutine drivers.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
Most helpful comment
A (much fancier) version of this might be usable to make accurate type definitions for
redux-saga. Currently, everything inredux-saganeeds explicit types (and hoping that you wrote the right ones) because the result of allyields isany.For
redux-saga, the interface would also need a way to say what is the expected result of ayieldwhen youyielda specific type, which is necessary for coroutine drivers.