Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Current status of typing generators in TS #13

Open
hax opened this issue May 24, 2022 · 1 comment
Open

Current status of typing generators in TS #13

hax opened this issue May 24, 2022 · 1 comment

Comments

@hax
Copy link
Member

hax commented May 24, 2022

function *g() {
  const x = yield 1
}

TS will say "yield' expression implicitly results in an 'any' type because its containing generator lacks a return-type annotation.(7057).

We could add return-type annotation, but because TNext is the third type param of Generator<T, TResult, TNext>, we need also specify the types of T and TResult which we normally want TS to infer.

We could also add type annotation to declaration or add as clause to yield expression:

const x: string = yield 1
// or
const x = (yield 1) as string

But the problem is we need to add such type annotations for every yield expressions. 😢

function.sent is just an expression, so it would still suffer the problem unless TS could fix microsoft/TypeScript#26242 or introduce some special syntax to annotate function.sent generally (which seems unlikely).

The alternative solution function *g(...args) receive (v) {} could solve the problem, it just use parameter syntax.


Another problem of TS is, even specify TNext type, TS still allow next() with no argument. I think this is because currently generator can't receive the first value, so people only use first next() to start the generator, so TS allow that to match practice.

Receive param syntax could solve this problem, though function.sent syntax could also (TS could check the presence of function.sent to eliminate this hole).

@Jack-Works
Copy link
Member

microsoft/TypeScript#43632

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants