Repository navigation
Boolean literal types and return type propagation for generators #2983
Description
Activity
- addedSuggestionAn idea for TypeScriptAn idea for TypeScript
on May 1, 2015 - addedIn DiscussionNot yet reached consensusNot yet reached consensus
on Jul 14, 2015 Boolean literal types are now available in #9407. Once that is merged we can update the return type of generators and iterators.
Reacted by Jason Freeman, Troy Gerwien, Brandon Bloom, tetsuo, Kirill Agalakov, Tylor Steinberger, Patrik Lundqvist, Artem Tyurin, soerenBoisen, Piyush Katariya and 3 moreReacted by Kitson Kelly, Troy Gerwien, Shayan Sayahi, tetsuo, Kirill Agalakov, Tylor Steinberger, Patrik Lundqvist, Flavio Vilante and 流浪大法师Does it allow to type async-like
yieldexpressions in libraries likecoorreact-saga?// getUser(): Promise<User> let user = yield getUser() // user: ?
Reacted by Violet Martin, monnef, Dan Wilt, Crhistian Ramirez, Gitowiec, Anton Novik, Richard Simpson, Ashlynne Mitchell, Laurin, Shane Yu and 14 moreStanislav Panferov (@s-panferov) unfortunately not. You are talking about the async-runner style of generator used by things like
coright?The generator proposal (#2873) doesn't offer much typing support for async-runner generators. In particular:
- All
yieldexpressions are typed asany, as you can see in the example comments below. This is actually a very complex problem and I tried tackling it with some ideas which are all there in Proposal for generators design #2873. This won't change with Number, enum, and boolean literal types #9407. And theTNexttype in the OP above won't solve this either, since in an async runner there is generally not a singleTNexttype, but rather the type of eachyieldexpression is a function of the type of thatyield's operand (egPromise<T>maps toT,Array<Promise<T>>maps toT[], etc). In particular the type of eachyieldexpression is generally unrelated to the types of the otheryieldexpressions in the body in an async-runner generator function. - The compiler infers a single
TYieldtype that must be the best common type among all theyieldoperands. For async runners there often is no such best common type, so such generators often won't compile until at least oneyieldoperand is cast toany. E.g. thefunction *barexample below doesn't compile for this reason. - Return types of generators are currently not tracked because without boolean literals, they can't be separated from the
TYieldtype. This is what will be solvable once Number, enum, and boolean literal types #9407 lands.
Example code:
interface User {id; name; address} interface Order {id; date; items; supplierId} interface Supplier {id; name; phone} declare function getUser(id: number): Promise<User>; declare function getOrders(user: User): Promise<Order[]>; declare function getSupplier(id: number): Promise<Supplier>; function* foo() { let user = yield getUser(42); // user is of type 'any' let user2 = <User> user; return user2; // This return type is not preserved } function* bar() { // ERROR: No best common type exists among yield expressions let user = yield getUser(42); // user has type 'any' let orders = yield getOrders(user); // orders has type 'any' let orders2 = <Order[]> orders; let suppliers = yield orders2.map(o => getSupplier(o.supplierId)); // suppliers has type 'any' let suppliers2 = <Supplier[]> suppliers; return suppliers2; // This return type is not preserved }
Reacted by JeroenNelen, Simon Friis Vindum, Aleksandr Chernyavenko, timm-aym, Dan Wilt, Berkay Yıldız, roman, Yijian Wang, 流浪大法师, Artur Udalov and 1 more- All
Troy Gerwien (@yortus) big thanks for the clarification!
All yield expressions are typed as any, as you can see in the example comments below. This is actually a very complex problem and I tried tackling it with some ideas which are all there in #2873. This won't change with #9407. And the TNext type in the OP above won't solve this either, since in an async runner there is generally not a single TNext type, but rather the type of each yield expression is a function of the type of that yield's operand (eg Promise maps to T, Promise[] maps to Promise<T[]>, etc). In particular the type of each yield expression is generally unrelated to the types of the other yield expressions in the body in an async-runner generator function.
Do you know if there is a tracking issue for this use-case? I think we definitely need to continue discussion, because this use-case is quite common and becomes more and more popular.
Reacted by monnef, Gitowiec, jarmo and 流浪大法师Stanislav Panferov (@s-panferov) no problem. I think there's just #2873. There's quite a lot of discussion about the async-runner use-case in there, but I think that the team wanted to focus on getting simpler use cases working initially. Since that issue is now closed, I guess you could open a new issue focused specifically on better typing for
co-style generators.DanielRosenwasser commented
on Aug 15, 2016 MemberMore actionsThis hasn't actually been fixed yet.
Reacted by Troy Gerwien, Kirill Agalakov, Ben, soerenBoisen, Moe Elsharif, Adam Pietrasiak, akay64, 流浪大法师, Douglas Nassif Roma Junior and Huy PhamDanielRosenwasser commented
on Aug 15, 2016 MemberMore actionsThe issue as I see it is that without #2175, this would be a breaking change. For example, you start out fixing
IteratorResult:interface IteratorYieldResult<Y> { done: false; value: Y; } interface IteratorReturnResult<R> { done: true; value: R; } type IteratorResult<Y, R> = IteratorYieldResult<Y> | IteratorReturnResult<R>
Now all of a sudden you need to introduce another type parameter to
Iterator:interface Iterator<Y, R> { next(value?: any): IteratorResult<Y, R>; return?(value?: any): IteratorResult<Y, R>; throw?(e?: any): IteratorResult<Y, R>; }
which infects
Iterable&IterableIterator:interface Iterable<Y, R> { [Symbol.iterator](): Iterator<Y, R>; } interface IterableIterator<Y, R> extends Iterator<Y, R> { [Symbol.iterator](): IterableIterator<Y, R>; }
These now break any users of
Iterators. For instance,Array's members needed to be fixed up to:interface Array<T> { /** Iterator */ [Symbol.iterator](): IterableIterator<T, undefined>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, T], undefined>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number, undefined>; /** * Returns an list of values in the array */ values(): IterableIterator<T, undefined>; }
JsonFreeman commented
on Aug 15, 2016 ContributorAuthorMore actionsYes I remember our long discussion about this. The tricky bit is that many users will just want to use for-of, spread and rest, which never use the R type. Those users will not care about R, only Y. Then there are some users who will call the iterator methods explicitly, and they will care about the R type. The art is in serving both use cases simultaneously. I think there needs to be a type with two type parameters, and another type with only one, where the second type argument is
any.Reacted by Gabe JohnsonI feel definitions using literal types is too complex for common interfaces because we need to explicitly assert a boolean literal type for now. We need more easy ways to use literal types.
function iter(): IteratorResult<void, void> { return { done: <true>true }; }
With respect to what Jason Freeman (@JsonFreeman) said according to the concern raised by Daniel Rosenwasser (@DanielRosenwasser), I experimented with a hypothetical typing of iterators that may return values.
Currently we have this:
interface IteratorResult<T> { done: boolean; value: T; } interface Iterator<T> { next(value?: any): IteratorResult<T>; return?(value?: any): IteratorResult<T>; throw?(e?: any): IteratorResult<T>; }
This can be changed to:
Sorry for names end with2, that's just for illustrationinterface IteratorYieldResult<Y> { done: false; value: Y; } interface IteratorReturnResult<R> { done: true; value: R; } type IteratorResult2<T, R> = IteratorYieldResult<T> | IteratorReturnResult<R>; // redefine IteratorResult through extended interface to preserve generic arity type IteratorResult<T> = IteratorResult2<T, any>; interface Iterator2<T, R, I> { next(value?: I): IteratorResult2<T, R>; return?(value: R): IteratorResult2<T, R>; throw?(e?: any): IteratorResult2<T, R>; } // redefine Iterator through extended interface to preserve generic arity type Iterator<T> = Iterator2<T, any, any>;
Open questions:
next(value: I)ornext(value?: I)- if
valueis optional then we will not be able to enforce strict typeIinyieldexpression in generators 👎 - if
valuewere not be optional then to allownext()we'd need to either typeI | undefinedor require consumer to work around likenext(undefined as I)👎
- if
return(value: R)strictly requiresvalueto be passed, right?
JsonFreeman commented
on Oct 5, 2016 ContributorAuthorMore actionsNice typing Igor Oleinikov (@Igorbek)!
I don't think the
returnparameter should be required. I get the impression that thereturnmethod is largely for cleanup, just executing anyfinallyclauses that correspond to try/catch blocks surrounding the execution point (for a generator in particular). Unless you have a yield expression in one of the finally blocks, the consumer will already have the value they want returned.For the
nextparameter, I think it has to be optional. Consider the language constructs for iterating (for-of, spread, etc). None of those constructs pass a parameter. If the generator really needs the parameter to be passed, then I think it is misleading to call it an iterator. It might be better to have a separate generator type for that, since the consumer will have to interact with the object in a different way.45 remaining items
incorrect typing around
returntype just bit me, wow this issues is oldReacted by Dziamid, Kirill Agalakov, Joe Calzaretta, Yifei Wang, Dom DiCicco, David Piper, Tylor Steinberger, ExE Boss, Fabrizio, Richard Simpson and 12 moreIf this is gonna be worked on, I think a nice easy win separate from typing the return value of generators would be to make the
returnandthrowmethods non-optional.
I’m writing a lot of code like:// having this function return an iterator type with non-optional `return` and // `throw` results in a type error function* gen(): IterableIterator<number> { yield 1; yield 2; yield 3; } // need an exclamation mark because return is optional, despite the fact // that the return method is always defined for generator objects. gen().return!();
- addedFixedA PR has been merged for this issueA PR has been merged for this issue
on Jul 8, 2019 - Reacted by Zak Henry, Igor Adrov, Flavio Vilante, Iorg, Plimeor and 流浪大法师Reacted by Brian Kim, Brandon Bil, Flavio Vilante, Iorg and 流浪大法师
Stanislav Panferov (@s-panferov) unfortunately not. You are talking about the async-runner style of generator used by things like
coright?The generator proposal (#2873) doesn't offer much typing support for async-runner generators. In particular:
- All
yieldexpressions are typed asany, as you can see in the example comments below. This is actually a very complex problem and I tried tackling it with some ideas which are all there in Proposal for generators design #2873. This won't change with Number, enum, and boolean literal types #9407. And theTNexttype in the OP above won't solve this either, since in an async runner there is generally not a singleTNexttype, but rather the type of eachyieldexpression is a function of the type of thatyield's operand (egPromise<T>maps toT,Array<Promise<T>>maps toT[], etc). In particular the type of eachyieldexpression is generally unrelated to the types of the otheryieldexpressions in the body in an async-runner generator function. - The compiler infers a single
TYieldtype that must be the best common type among all theyieldoperands. For async runners there often is no such best common type, so such generators often won't compile until at least oneyieldoperand is cast toany. E.g. thefunction *barexample below doesn't compile for this reason. - Return types of generators are currently not tracked because without boolean literals, they can't be separated from the
TYieldtype. This is what will be solvable once Number, enum, and boolean literal types #9407 lands.
Example code:
interface User {id; name; address} interface Order {id; date; items; supplierId} interface Supplier {id; name; phone} declare function getUser(id: number): Promise<User>; declare function getOrders(user: User): Promise<Order[]>; declare function getSupplier(id: number): Promise<Supplier>; function* foo() { let user = yield getUser(42); // user is of type 'any' let user2 = <User> user; return user2; // This return type is not preserved } function* bar() { // ERROR: No best common type exists among yield expressions let user = yield getUser(42); // user has type 'any' let orders = yield getOrders(user); // orders has type 'any' let orders2 = <Order[]> orders; let suppliers = yield orders2.map(o => getSupplier(o.supplierId)); // suppliers has type 'any' let suppliers2 = <Supplier[]> suppliers; return suppliers2; // This return type is not preserved }
As it is not an easy task to make TypeScript able to handle generator functions like they are used by Redux Saga, I have come up with a workaround that works for me.
You can see it here: https://github.com/ilbrando/redux-saga-typescriptReacted by CallMeLaNN and 流浪大法师Reacted by Brian Kim, CallMeLaNN, Max, Eugene Oskin, 流浪大法师 and Damilola Majek- All
ilbrando another alternative: https://github.com/agiledigital/typed-redux-saga
Reacted by CallMeLaNN, Near Huscarl, 流浪大法师 and Weiyuan WuThank you Daniel Nixon (@danielnixon) this is a really clever solution.

This suggestion has a few pieces:
trueandfalse, in a fashion similar to Singleton types under the form of string literal types #1003nextmethod that returns{ done: false; value: TYield; } | { done: true; value: TReturn; }, where TYield is inferred from the yield expressions of a generator, and TReturn is inferred from the return expressions of a generator.{ done: false; value: TYield; } | { done: true; value: any; }to be compatible with generators.yield*would only pick the value associated with done being false.yield*expression would pick the value associated with done being true.yieldexpression. This would be TNext, and would be the type of the parameter for the next method on a generator.The generator type would look something like this: