DEV Community

loading...

Discussion on: Generators in Javascript: How to use them

Collapse
tassoevan profile image
Tasso Evangelista • Edited

It's a shame that generators kinda look terrible in TypeScript.

const output = yield input;
Enter fullscreen mode Exit fullscreen mode

It's impossible to properly type output based on input. You've to use a wide type for both and force type narrowing by hand.

Collapse
tylors profile image
Tylor Steinberger

If you switch to yield * the type do work surprisingly well.

For example, github.com/briancavalier/fx-ts

Collapse
tassoevan profile image
Tasso Evangelista

Hmmm, I haven't wondered it! It surely restricts a little what you can express in code, but I not sure about what is lost.

Thread Thread
tylors profile image
Tylor Steinberger

Thankfully it shouldn't! There are still yields happening under the hood, but in Generator<Yield, Return, Next>, Next is the return value of individual yields which there can be many (source of the issue is they must be a product type A & B), while Return is the value returned when .next() returns done:true, and since there is only 1 value there we don't have to worry about the same typing complexities.

It's very easy to convert from one to the other. function*(thing) { const x = yield thing; return x}