You-Don-t-Know-TS icon indicating copy to clipboard operation
You-Don-t-Know-TS copied to clipboard

1.3.实现Awaited

Open lyric-zemin opened this issue 2 years ago • 1 comments

/* _____________ 你的代码 _____________ */

type MyAwaited<T> = T extends Promise<infer U>
  ? MyAwaited<U>
  : T extends { then: (p: (arg: infer K) => any) => any }
  ? K
  : T;

/* _____________ 测试用例 _____________ */
import type { Equal, Expect } from '@type-challenges/utils';

type X = Promise<string>;
type Y = Promise<{ field: number }>;
type Z = Promise<Promise<string | number>>;
type Z1 = Promise<Promise<Promise<string | boolean>>>;
type T = { then: (onfulfilled: (arg: number) => any) => any };

type cases = [
  Expect<Equal<MyAwaited<X>, string>>,
  Expect<Equal<MyAwaited<Y>, { field: number }>>,
  Expect<Equal<MyAwaited<Z>, string | number>>,
  Expect<Equal<MyAwaited<Z1>, string | boolean>>,
  Expect<Equal<MyAwaited<T>, number>>
];

// @ts-expect-error
type error = MyAwaited<number>;

lyric-zemin avatar Dec 02 '22 05:12 lyric-zemin

nice work!

paiDaXing-web avatar Sep 21 '23 09:09 paiDaXing-web