Skip to content

Generator functions which have a return type of a union of Iterator/AsyncIterator have a yield type of never #34984

Open
@brainkim

Description

@brainkim

TypeScript Version: 3.7.2

Search terms: generator iterator asynciterator type union never

Code

example.ts

type NumberIterator = Iterator<number> | AsyncIterator<number>;
type NumberGenerator = Generator<number> | AsyncGenerator<number>;

function *numbers(): NumberIterator {
    yield 1;
}

A type alias which is a union of Iterator and AsyncIterator is used as the return type of a synchronous generator.

Expected behavior:

Code compiles.

Actual behavior:

example.ts(5,11): error TS2322: Type '1' is not assignable to type 'never'.

If you replace NumberIterator with NumberGenerator as the return type the function above, the code correctly type-checks. Something is wrong here.

Playground Link:

https://www.typescriptlang.org/play/index.html?target=99&ssl=5&ssc=2&pln=1&pc=1#code/C4TwDgpgBAcgrgWwEYQE4ElhoIbAPapQC8UmO+qAPAHaIqoB8UAPlAIIDOI1AxmargI06aBgG4AUBIBmcXsACWealABUtZGg4AKAJQAuWCIxYBFKAG8JUG1BAKIAGwAmUAIySAvkA

The playground link won’t work because the playground doesn’t support async iterators yet (microsoft/TypeScript-Website#15).

Related Issues:
#30790 Strongly-typed iterator PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs InvestigationThis issue needs a team member to investigate its status.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions