Skip to content

Type inference is lose inside a promise #27001

@michaeljota

Description

@michaeljota

TypeScript Version: 3.1.0-dev.201xxxxx

Search Terms:

  • type literal promises
  • type inferred promises

Code

interface ResponseA {
    type: 'A',
    payload: any,
}

interface ResponseB {
    type: 'B',
    payload: any,
}

type ResponseKind = ResponseA | ResponseB;

// Does not work in strict mode
async function returnResponseAsync(): Promise<ResponseKind> {
    const type = 'A';
    const payload = {};

    return await {
        type, // type is 'string' type
        payload
    }
}

// Works in strict mode
function returnResponse(): ResponseKind {
    const type = 'A';
    const payload = {};

    return {
        type, // type is 'A' type
        payload
    }
}

This is a minimum reproducible code but I found this working with a complex scenario of observables and promises. However, the bug is still reproducible, because the type is being lose.

Expected behavior:

Inside the promise type type should be inferred as well.

Actual behavior:

Throws because string is not assignable to neither A or B.

Playground Link:

Link using async/await

Link with Promise.resolve

Link with Observable

Related Issues:

Workaround:

Just type the variable with a literal type.

async function returnResponseAsync(): Promise<ResponseKind> {
    const type: 'A' = 'A';
    const payload = {};

    return await {
        type, // type is 'A' type
        payload
    }
}

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptGood First IssueWell scoped, documented and has the green lightHelp WantedYou can do this

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions