Typescript Series - Awaited Type
Sarmun Bustillo
Posted on August 21, 2022
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
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;
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
Posted on August 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
October 4, 2024