Skip to content

Latest commit

 

History

History
37 lines (28 loc) · 1.16 KB

type-promise-results-with-the-awaited-type.md

File metadata and controls

37 lines (28 loc) · 1.16 KB

Type Promise Results With the Awaited Type

TypeScript 4.5 introduces the Awaited type which can be used to model the resulting type of Promise and async/await code.

The release notes give a couple helpful examples which I'll share:

// A = string
type A = Awaited<Promise<string>>;

// B = number
type B = Awaited<Promise<Promise<number>>>;

// C = boolean | number
type C = Awaited<boolean | Promise<number>>;

This can be taken a step further with an existing typed function and the help of the ReturnType type.

// getPosts' return type Promise<Array<Post>>
import {getPosts} from './getPost'

// type: { posts: Array<Post> }
type LoaderData = {
  posts: Awaited<ReturnType<typeof getPosts>>;
}

It gets the full typeof of getPosts, whittles that down to the ReturnType, and then Awaited unwraps the promise. I learned this from the Remix blog tutorial.