Skip to content

return type of function returning a promise or a an empty object is incorrectly inferred unless promise is awaitedΒ #54524

Closed as not planned
@jacekkarczmarczyk

Description

@jacekkarczmarczyk

Bug Report

πŸ”Ž Search Terms

function, return type, await, empty object

πŸ•— Version & Regression Information

  • This changed between versions 4.9 and 5.0

Nothing in the TS 5.0 release notes seems to be related to this change of the behaviour

⏯ Playground Link

πŸ’» Code

declare function getData(): Promise<{ [key in string]: unknown }>;

const fn = async (test: boolean) => test ? getData() : {}
//    ^? const fn (test: boolean) => Promise<{ [key in string]: unknown }>    in TS 4.9
//    ^? const fn (test: boolean) => Promise<{}>     in TS 5.0

const fnAwaited = async (test: boolean) => test ? await getData() : {}
//    ^? const fnAwaited (test: boolean) => Promise<{ [key in string]: unknown }>    in TS 4.9, 5.0

playground, TS 4.9

playground, TS 5.0

πŸ™ Actual behavior

Function's return type is Promise<{}>

πŸ™‚ Expected behavior

Function's return type should be Promise<{ [key in string]: unknown }>

Here's the code that's more close to the actual use case:

declare function getData(): Promise<{ [key in string]: unknown }>;
declare function useAsyncComputed<R> (load: () => Promise<R>, defaultValue: R): R;
declare const test: boolean;

const foo = useAsyncComputed(async () => test ? getData() : {}, {});

console.log(foo.whatever);

playground, TS 4.9

playground, TS 5.0

This is a pattern I'm using in multiple places in my app with TS 4.9, and if I wanted to upgrde to TS 5.0 I'd need to add await before every getData() call, which I know I can do automatically using eslint, but I don't think that should be necessary

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions