Skip to main content

Awaited

introduction#

If we have a type which is wrapped type like Promise. How we can get a type which is inside the wrapped type? For example if we have Promise<ExampleType> how to get ExampleType?

This question is ported from the original article by @maciejsikora

View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type Awaited<T> = any;
 
/* _____________ Test Cases _____________ */
type X = Promise<string>;
type Y = Promise<{ field: number }>;
 
type cases = [
Expect<Equal<Awaited<X>, string>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Awaited<Y>, { field: number }>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type Awaited<T> = any;
 
/* _____________ Test Cases _____________ */
type X = Promise<string>;
type Y = Promise<{ field: number }>;
 
type cases = [
Expect<Equal<Awaited<X>, string>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Awaited<Y>, { field: number }>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
take the challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;
Try
ts
type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;
Try
view more solutions