DEV Community

Cover image for Typescript Series - Awaited Type
Sarmun Bustillo
Sarmun Bustillo

Posted on

Typescript Series - Awaited Type

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

If we have a type which is wrapped type like Promise. How we can get a type which is inside the wrapped type?

Let's see a couple of examples

type Example1 = Promise<string>
type Example2 = Promise<{ field: number }>
type Example3 = Promise<Promise<string | number>>


type Result1 = MyAwaited<Example1> // string
type Result2 = MyAwaited<Example2> // { field: number }
type Result3 = MyAwaited<Example3> // string | number

Enter fullscreen mode Exit fullscreen mode

Worth noticing here, that we should also take nested promises into account.

How would this type would look like?

type MyAwaited<Type> = Type extends Promise<infer K> 
? MyAwaited<K> : Type;
Enter fullscreen mode Exit fullscreen mode

Understanding the infer keyword

The infer keyword can be used within a condition in a conditional type to put the inferred type into a variable. That inferred variable can then be used within the conditional branches.

Let's break it down:

Type extends Promise<infer K> Here we check if Type extends a Promise type and we infer the type that is wrapped inside.

If it does extend it, meaning our Type is of type Promise (ex: Promise>), then we use recursion to check again MyAwaited<K>

if it does not extend it, then we just simply return the Type

Thank you!

you can find me here My Twitter

Top comments (0)