benhowdle89
benhowdle89

Reputation: 37454

TypeScript ReturnType of async function

I have this example:

async function main() {
  const foo = async () => {
    return "foo";
  };

  let fooResult: ReturnType<typeof foo>;

  fooResult = await foo();
}

main();

But TS fails to compile with let fooResult: Promise<string> Type 'string' is not assignable to type 'Promise<string>'

What am I missing in typing the return type of an async function?

Upvotes: 5

Views: 1249

Answers (1)

mickl
mickl

Reputation: 49945

You need Awaited to define the type based on an asynchronous function which returns Promise<string>:

let fooResult: Awaited<ReturnType<typeof foo>>; //string

Playground

The await foo(); statement unwraps the promise and returns a string type so fooResult has to be a string type as well

Upvotes: 9

Related Questions