1
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?

More than 3 years have passed since last update.

infer(conditional types)を使って型からArrayを引っ剥がす

Posted at

例えば

type Dogs = Array<{name: string, age: number}>

みたいな既存型がある時に

{name: string, age: number}

この部分を得たいという事が稀によくあります。

type Dog = {name: string, age: number}
type Dogs = Array<Dog>

最初からDogを定義しておいて、そのDogを元にDogsを作っていれば良かったじゃん?と言われるとそれはそうなんですが、外からやってくる型(例えばGraphQLから生成されたPick<Dog, 'name' | 'age'>みたいなアドホックな型定義だとか)の場合はそうも言ってられません。

そういう時にはinfer(conditional types)を使ってArray<T>T部分をキャプチャして得る事ができます。

type Flatten<T> = T extends Array<infer U> ? U : never
type Dog = Flatten<Dogs>

この例ではArrayを引っ剥がしましたが、Arrayと同様にPromiseだとかMaybe(type Maybe<T> = T | null)だとかを引っ剥がすのにも使えたり、ビルトインのユーティリティ型であるReturnType定義なんかにも使われています。

1
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
1
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?