LoginSignup
6
7

More than 3 years have passed since last update.

【TypeScript】PickとOmit

Posted at

TypeScript 初心者です。
React の型定義で Pick と Omit について学習したのでまとめてみました。

Pick

Pick<T, K> は既に存在する T 型の中から K で選択したプロパティのみを含んだ新たな型を構築する。
下記の例では、User型の nameemail のみを含んだ UserItem型を作成している。

type User = {
  id: string;
  name: string;
  email: string;
  address: string;
};

type UserItem = Pick<User, "name" | "email">;
// | で複数指定可

const user: UserItem = {
  name: "hoge",
  email: "hoge@example.com",
};

console.log(user); // => {name: "hoge", email: "hoge@example.com"}

Omit

Omit<T, K>は既に存在する T 型の中から K で選択したプロパティを除いた新たな型を構築する。
下記の例では、User から idaddress を除いた UserItem型を作成している。

type User = {
  id: string;
  name: string;
  email: string;
  address: string;
};

type UserItem = Omit<User, "id" | "address">;

const user: UserItem = {
  name: "hoge",
  email: "fuga",
};

console.log(user); //=> {name: "hoge", email: "hoge@example.com"}
6
7
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
6
7