diff --git a/README.md b/README.md index 4d46a29..c638d3c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1198 TILs and counting..._ +_1199 TILs and counting..._ --- @@ -1104,6 +1104,7 @@ _1198 TILs and counting..._ - [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) - [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md) +- [Type Promise Results With The Awaited Type](typescript/type-promise-results-with-the-awaited-type.md) - [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md) - [Zero-Config Environments For Trying Out Types](typescript/zero-config-environments-for-trying-out-types.md) diff --git a/typescript/type-promise-results-with-the-awaited-type.md b/typescript/type-promise-results-with-the-awaited-type.md new file mode 100644 index 0000000..dacd720 --- /dev/null +++ b/typescript/type-promise-results-with-the-awaited-type.md @@ -0,0 +1,37 @@ +# Type Promise Results With the Awaited Type + +[TypeScript 4.5 introduces the `Awaited` +type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#the-awaited-type-and-promise-improvements) +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: + +```typescript +// A = string +type A = Awaited>; + +// B = number +type B = Awaited>>; + +// C = boolean | number +type C = Awaited>; +``` + +This can be taken a step further with an existing typed function and the help +of the [`ReturnType` +type](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype). + +```typescript +// getPosts' return type Promise> +import {getPosts} from './getPost' + +// type: { posts: Array } +type LoaderData = { + posts: Awaited>; +} +``` + +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](https://remix.run/docs/en/v1/tutorials/blog#a-little-refactoring).