Skip to content

Support promise-like types in contextual return type of async function#27255

Closed
rbuckton wants to merge 3 commits intomasterfrom
fix24629
Closed

Support promise-like types in contextual return type of async function#27255
rbuckton wants to merge 3 commits intomasterfrom
fix24629

Conversation

@rbuckton
Copy link
Copy Markdown
Contributor

This changes the contextual type we use for a return expression in an async function. Prior to this change, we would infer {} for the type argument to Promise below:

interface Obj { key: "value"; }

function fn1(): Promise<Obj> {
    // ok: 'Promise<T>' is contextually typed to 'Promise<Obj>'
    return new Promise(resolve => { resolve({ key: "value" }); });
}

async function fn2(): Promise<Obj> {
    // ok: return expression is contextually typed to 'Obj'.
    return { key: "value" }; 
}

async function fn3(): Promise<Obj> {
    // error: '{}' is not assignable to type 'Obj'.
    return new Promise(resolve => { 
        resolve({ key: "value" });
    });
}

This is because we use the "awaited type" Obj for the return type Promise<Obj> as the contextual type. With this change, we use Obj | PromiseLike<Obj> as the contextual type:

interface Obj { key: "value"; }

function fn1(): Promise<Obj> {
    // ok: 'Promise<T>' is contextually typed to 'Promise<Obj>'
    return new Promise(resolve => { resolve({ key: "value" }); });
}

async function fn2(): Promise<Obj> {
    // ok: return expression is contextually typed to 'Obj | PromiseLike<Obj>'.
    return { key: "value" }; 
}

async function fn3(): Promise<Obj> {
    // ok: 'Promise<T>' is contextually typed to 'Promise<Obj>'
    return new Promise(resolve => { 
        resolve({ key: "value" });
    });
}

Fixes #24629

@rbuckton rbuckton added this to the TypeScript 3.1 milestone Sep 21, 2018
@rbuckton rbuckton changed the title Fix24629 Support promise-like types in contextual return type of async function Sep 21, 2018
@rbuckton
Copy link
Copy Markdown
Contributor Author

Closing as this was inadvertently opened against 'master'.

@rbuckton rbuckton closed this Sep 21, 2018
@microsoft microsoft locked as resolved and limited conversation to collaborators Oct 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Marking a function async changes how return type annotation effects type inference

3 participants