LoginSignup
3
3

More than 3 years have passed since last update.

【TypeScript】Utility TypesのPickを深く理解する

Last updated at Posted at 2021-03-07

この記事は何?

この記事は、Utility Typesの一つであるPickについて深く理解する記事です。
Utility Typesってそもそも何?という型(方)は以下の記事を御覧ください🙇🏻
👉 TypeScriptのUtility Typesを理解して活用する

そもそも、TypeScriptって何?って型は以下を御覧ください
👉 JavaScriptを知っている方がTypeScriptをなんとなく理解するための記事① ~はじめに~

Pick<Type, Keys>とは

TypeScript公式には以下のように書かれています。

Constructs a type by picking the set of properties Keys from Type.
タイプからプロパティキーのセットを選択することにより、タイプを構築します。
https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys

これはつまり、ある型からその中にあるプロパティを指定して、新たに型を作ることを示しています。
具体的に言うと、例えばPokemon型があるとします。

interface Pokemon {
  height: number;
  weight: number;
  name: string;
  description: string;
  type: string;
}

ここで、Picachu型を作るとします。
ピカチューを表現するためには、名前と可愛いという情報だけで十分です。
そのため、Picachu型は以下のように作りたいです。

interface Picachu {
  name: string;
  description: string;
}

const favoritePockemon: Picachu = {
  name: "ピカチュー",
  description: "可愛い";
}

ここで、Picachu型にあるプロパティはPokemon型のプロパティと重複していることがわかります。
プロパティとはnameおよびdescriptionのことです。
これらのプロパティをもう一度書くのは冗長そうです🤔

そこで、Pick<Type, Keys>を利用します。
Pick<Type, Keys>は次のように利用します。

type Picachu = Pick<Pokemon, "name" | "description">

そうです、Pokemon型の中からプロパティを取り除いて(Pick)あげれば良いです。
今回は、Pokemon型からnamedescriptionを取り除いて、新しい型を生成しました。

これにより、最終的には以下のようにPickを活用できます。

type Picachu = Pick<Pokemon, "name" | "description">

const favoritePockemon: Picachu = {
  name: "ピカチュー",
  description: "可愛い";
}

React&TypeScriptなどで使いたい場合は、以下のように書けば良さそうです。

import { Pokemon } from '~~'

type Picachu = Pick<Pokemon, "name" | "description">

const PicachuComponent: React.FC<Picachu> = (props) => {
 ...
}

このようにピカチューは可愛いというオブジェクトを簡単に記述することが出来ました。

おわりに

今回は、Pickについて書いてみました。
是非、ご活用ください!

参考

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