Skip to content

Generator return type annotation doesn’t contextually type return statement #35995

Closed
@bwiklund

Description

@bwiklund

TypeScript Version: 3.7.2, nightly

Search Terms:
Generator can't infer that string belongs to a union in return type

Code

type FooType = { a: 'foo' };
type G = Generator<any, FooType, any>;

function* broken(): G {
    return {
        a: 'foo'
/*
Type 'string' is not assignable to type '"foo"'.(2322)
input.ts(1, 18): The expected type comes from property 'a' which is declared here on type 'FooType'
*/
    }
}

function* workaround1(): G {
    const rval: FooType = { a: 'foo' };
    return rval;
}

function* workaround2(): G {
    return {
        a: 'foo' as const
    }
}

Expected behavior:
The return type shouldn't need these workarounds to know that 'foo' belongs to the union type.

Actual behavior:
Error described above. I included a couple workarounds that don't seem like they should be necessary, but are.

Playground Link: http://www.typescriptlang.org/play/#code/C4TwDgpgBAYg9nAKuaBeKBvKBDAXFAcgDMECoBfAbgChRIoBxKdBiAOwgCdtg5OAebGxAAaWAmSQxQkAD4a1IgFc2AY2ABLOGwBUUAEac4Aa3YAKAJT4mGalHtROEYEs5tMdh17yEScAp725NTBiirqWrpQAO58xthGKgAmAIyW1h5eqtoAzsCOAG7YADb48EgozJg4+MSkFDReTi5uhSU0ocpqmtp6sZzxiWxJAEzpjJkOza7utl7etX5k2DlQ2Wx5gRQhQA

Related Issues: None as far as i could find

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueRescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions