Skip to content

Commit 164ae27

Browse files
committed
add Awaited TS challenge
1 parent 6379a7f commit 164ae27

File tree

2 files changed

+66
-38687
lines changed

2 files changed

+66
-38687
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
189 - Awaited
3+
-------
4+
by Maciej Sikora (@maciejsikora) #easy #promise #built-in
5+
6+
### Question
7+
8+
If we have a type which is wrapped type like Promise. How we can get a type which is inside the wrapped type?
9+
10+
For example: if we have `Promise<ExampleType>` how to get ExampleType?
11+
12+
```ts
13+
type ExampleType = Promise<string>
14+
15+
type Result = MyAwaited<ExampleType> // string
16+
```
17+
18+
> This question is ported from the [original article](https://dev.to/macsikora/advanced-typescript-exercises-question-1-45k4) by [@maciejsikora](https://github.com/maciejsikora)
19+
20+
> View on GitHub: https://tsch.js.org/189
21+
*/
22+
23+
/* _____________ Your Code Here _____________ */
24+
25+
type PromiseLike = {
26+
then: (onfulfilled: (arg: number) => unknown) => unknown;
27+
};
28+
29+
type MyAwaited<T extends Promise<unknown> | PromiseLike> = T extends
30+
| Promise<infer R>
31+
| PromiseLike
32+
? R extends Promise<unknown>
33+
? MyAwaited<R>
34+
: R
35+
: T;
36+
37+
type ExampleType = Promise<string>;
38+
39+
type Result = MyAwaited<ExampleType>; // string
40+
41+
/* _____________ Test Cases _____________ */
42+
import type { Equal, Expect } from "@type-challenges/utils";
43+
44+
type X = Promise<string>;
45+
type Y = Promise<{ field: number }>;
46+
type Z = Promise<Promise<number | string>>;
47+
type Z1 = Promise<Promise<Promise<string | boolean>>>;
48+
type T = { then: (onfulfilled: (arg: number) => any) => any };
49+
50+
type cases = [
51+
Expect<Equal<MyAwaited<X>, string>>,
52+
Expect<Equal<MyAwaited<Y>, { field: number }>>,
53+
Expect<Equal<MyAwaited<Z>, string | number>>,
54+
Expect<Equal<MyAwaited<Z1>, string | boolean>>,
55+
Expect<Equal<MyAwaited<T>, number>>
56+
];
57+
58+
// @ts-expect-error
59+
type error = MyAwaited<number>;
60+
61+
/* _____________ Further Steps _____________ */
62+
/*
63+
> Share your solutions: https://tsch.js.org/189/answer
64+
> View solutions: https://tsch.js.org/189/solutions
65+
> More Challenges: https://tsch.js.org
66+
*/

0 commit comments

Comments
 (0)