Skip to content

Typing a generator results in unexpected undefined type #2080

@jlongster

Description

@jlongster

Best way to describe this is with an example:

declare var run: () => void

type Result = {
  id: string,
  value: number
}

function setBreakpoint() : Promise<Result> {
  return new Promise((resolve, reject) => {
    resolve({ id: "hi", value: 5 });
  });
}

function* foo() : Generator<Promise<Result>, Object, Result> {
  const { id } = yield setBreakpoint();
  return { id: id };
}

console.log(run(foo()));

The above gives this error:

main.js:52
 52:   const { id } = yield setBreakpoint();
               ^^ property `id`. Property cannot be accessed on possibly undefined value
 51: function* foo() : Generator<Promise<Result>, Object, Result> {
                                                                  ^ undefined

If I change the setBreakpoint line to this:

  const { id } = (yield setBreakpoint(): Result);

It's clear that somehow the result of the yield is getting an undefined type:

main.js:51
 51: function* foo() : Generator<Promise<Result>, Object, Result> {
                                                                  ^ undefined. This type is incompatible with
 52:   const { id } = (yield setBreakpoint(): Result);
                                              ^^^^^^ object type

I think it's also not pointing to the right place where it's getting the undefined type.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions