Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get TypeScript to automatically infer the type of the result of a `yield` call?

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).

like image 396
Carl Patenaude Poulin Avatar asked Jul 08 '16 19:07

Carl Patenaude Poulin


1 Answers

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.

like image 51
Retsam Avatar answered Oct 15 '22 20:10

Retsam