1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【図解】【初心者向け】TypeScriptの便利なユーティリティ型 - OmitとPickの違いを解説(1分で読める)

Posted at

TypeScriptのユーティリティ型であるOmitPickの違いをめっちゃ簡単に解説します。

Pick<T, K>

Pickはその名の通り、既存の型から指定したプロパティを 選び取って(Pick) 、新しい型を作成します。

image.png

// 元となる型
interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

// User型から 'id' と 'name' を選び取って新しい型を作成
type UserSummary = Pick<User, 'id' | 'name'>;

// 結果として、この型と同じになる
// interface UserSummary {
//   id: number;
//   name: string;
// }

Omit<T, K>

OmitPick とは逆に、既存の型から指定したプロパティを 取り除いて(Omit) 、その残り全てを使って新しい型を作成します。

image.png

// 元となる型
interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

// User型から 'email' を取り除いて新しい型を作成
type UserForPublic = Omit<User, 'email'>;

// 結果として、この型と同じになる
// interface UserForPublic {
//   id: number;
//   name: string;
//   age: number;
// }

まとめ

Pick Omitを使いこなすことによって型の定義がDRY(Don't Repeat Yourself)になり、より安全で保守性の高いコードを書くことが出来ます。

「この型とこの型ほとんど同じだけど、一部のプロパティだけ違うなー」となったらPick Omitを使ってみましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?