tc39 / proposal-function.sent

Generator function.sent Meta Property
MIT License
37 stars 6 forks source link

Current status of typing generators in TS #13

Open hax opened 2 years ago

hax commented 2 years ago
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 https://github.com/microsoft/TypeScript/issues/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 commented 2 years ago

https://github.com/microsoft/TypeScript/issues/43632