0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

type-challenges解いてみた 初級 189 easy-awaited編

Posted at

問題


Promise ライクな型が内包する型をどのように取得すればよいでしょうか。

例えば:`Promise<ExampleType>`という型がある場合、どのようにして ExampleType を取得すればよいでしょうか。

```ts
type ExampleType = Promise<string>

type Result = MyAwaited<ExampleType> // string
```

回答

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

ちょっと解説

  • T extends PromiseLike<infer U>
    もし T が PromiseLike であるなら、その中身の型を U として推論するという意味です。

  • MyAwaited<U>
    ネストしている場合に対応するため、再帰させています。

  • PromiseLike
    その名前の通り、擬似的なPromise型です。
    これは自分もよくわかっていないので深く掘りたい...

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?