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?

TypeScriptのPickとOmitを理解する

1
Last updated at Posted at 2026-01-13

Pick

概要

Pick<T, K> は、

T から指定したキー K だけを取り出した新しい型を作るユーティリティ型です。

サンプルコード

type SimpleProfile = Pick<DetailedProfile, "name" | "weight">;

// type SimpleProfile = {
//     name: string;
//     weight: number;
// }

DetailedProfile の中から

nameweight だけを抜き出した型が作られています。

Pick の定義

type Pick<T, K extends keyof T> = { [Pin K]: T[P]; }

何をしているか

  • K extends keyof T
    • KT が持つキーのみ指定できる
  • [P in K]
    • K に含まれるキーを1つずつ取り出す
  • T[P]
    • 元の型 T から対応するプロパティ型を参照する

つまり、

指定したキーだけで新しいオブジェクト型を再構築している

という仕組みです。

Omit

概要

Omit<T, K> は、

T から指定したキー K を除外した新しい型を作るユーティリティ型です。

サンプルコード

type SmallProfile = Omit<DetailedProfile, "height">;

// type SmallProfile = {
//     name: string;
//     weight: number;
// }

height プロパティだけを除外し、

残りの nameweight が保持されています。

Omit の定義

type Omit<T, K extends keyof any> = { [PinExclude<keyof T, K>]: T[P]; }

何をしているか

  • keyof T
    • T が持つすべてのキーのユニオン型
  • Exclude<keyof T, K>
    • その中から K を取り除く
  • [P in ...]: T[P]
    • 残ったキーだけで型を再構築

つまり Omit は、

「keyof T」→「Exclude」→「Pick 的な再構築」

という流れで動いています。

Pick と Omit の関係

  • Pick欲しいものを指定する
  • Omitいらないものを指定する

内部的には、

OmitExclude + Pick 的な処理で実装されています。

// イメージ
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;

使い分けの目安

  • プロパティが少なく、欲しいものが明確Pick
  • プロパティが多く、不要なものだけ決まっているOmit

まとめ

  • Pick指定したキーだけを抽出
  • Omit指定したキーを除外
  • どちらも Mapped Typeskeyof を使って実装されている
  • OmitExclude を内部で利用している

参考

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?