Skip to content

Generator type inference error #14043

Closed
Closed
@weswigham

Description

@weswigham

TypeScript Version: 2.1.6 and 2.2.0-dev.20170213

Code

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": true,
        "sourceMap": true
    }
}

test.ts:

export interface StrategicState {
    lastStrategyApplied?: string;
}

export function strategy<T extends StrategicState>(stratName: string, gen: (a: T) => IterableIterator<T | undefined>): (a: T) => IterableIterator<T | undefined> {
    return function*(state) {
        for (const next of gen(state)) {
            if (next) {
                next.lastStrategyApplied = stratName;
            }
            yield next;
        }
    }
}

export interface Strategy<T> {
    (a: T): IterableIterator<T | undefined>;
}

export interface State extends StrategicState {
    foo: number;
}

export const Nothing: Strategy<State> = strategy("Nothing", function*(state: State): IterableIterator<State | undefined> {
    return state;
});

Expected behavior:
Compiles without error.

Actual behavior:
On line 24, on the generator star: Generator implicitly has type 'IterableIterator<any>' because it does not yield any values. Consider supplying a return type.. This is unfixable without a terrible hack (add a line with the text if (!!false) yield state; to the top of the generator body), as there is already a return type specified. Actually, the return type (and argument type) should be inferred from the type annotation on the LHS of the equals sign and the strategy function signature (and the return type should not be required), but its not, though that's possibly a separate issue.

Activity

added this to the TypeScript 2.3 milestone on Feb 14, 2017
assigned
and
yuit
and unassigned on Feb 14, 2017
yuit

yuit commented on Feb 22, 2017

@yuit
Contributor

hi @weswigham !!! 🐱 This turned out to be an issue from how we aggregate return type from function body. We have a check for generator that only aggregate return type from yield expression...

added
FixedA PR has been merged for this issue
on Feb 22, 2017
locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @yuit@weswigham@rbuckton@mhegazy

        Issue actions

          Generator type inference error · Issue #14043 · microsoft/TypeScript