这是indexloc提供的服务,不要输入任何密码
Skip to content

189 - Awaited (🎥 Video Explanation and Solution) #21536

@dimitropoulos

Description

@dimitropoulos

189 - Awaited

Awaited is a nice early look at how recursive types look in TypeScript. Hopefully, by the end of this challenge you are starting to see how powerful TypeScript's type system is. It feels magical if you only see the tests, but if you see a solution it should make more sense.

🎥 Video Explanation

Release Date: 2023-01-08 19:00 UTC

Awaited

🔢 Code

import type { Equal, Expect } from "./test-utils";

type A1 = MyAwaited<Promise<string>>
type B1 = string;
type C1 = Expect<Equal<A1, B1>>;

type A2 = MyAwaited<Promise<{ field: number }>>
type B2 = { field: number };
type C2 = Expect<Equal<A2, B2>>;

type A3 = MyAwaited<Promise<Promise<string | number>>>
type B3 = string | number;
type C3 = Expect<Equal<A3, B3>>;

type A4 = MyAwaited<
  Promise<Promise<Promise<string | boolean>>>
>
type B4 = string | boolean;
type C4 = Expect<Equal<A4, B4>>;

// @ts-expect-error(2344)
type E1 = MyAwaited<number>;

// ============= Your Code Here =============
type MyAwaited<T extends Promise<unknown>> =
  T extends Promise<infer U>
  ? U extends Promise<unknown>
    ? MyAwaited<U>
    : U
  : T
;

type MyAwaited<T> =
  T extends PromiseLike<infer P>
  ? P
  : never
;

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions