In the following code example:
function* gen() {
let v = yield Promise.resolve(0);
return v;
}
The type of v
is inferred to be any
. I'm wondering if there's a way to get it to infer a different type (say, number
) based on contextual clues.
I know that in this specific scenario I can use async
/await
instead, but I'm wondering about the general case (when not working with promises).
Unfortunately, Typescript just doesn't support this right now. And there doesn't really appear to be a good workaround other than simply putting a type annotation on every yield
statement:
function* gen() {
let v: number = yield Promise.resolve(0);
return v;
}
It's a tricky problem to solve, as the value returned by yield
statements is entirely dependent on the semantics of whatever is consuming the generator. I know that yield Promise.resolve(0)
will eventually return a number only because I know the semantics of coroutine
, but v
really could be anything.
But hopefully Typescript will add support for declaring these relationships as part of the type of the generator itself. Here's a relevant github issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With