Reputation: 37454
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
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
The await foo();
statement unwraps the promise and returns a string
type so fooResult
has to be a string
type as well
Upvotes: 9