0
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 ユーティリティ型 まとめ

Last updated at Posted at 2024-08-18

TypeScriptのユーティリティ型(utility type)とは

型から別の型を導き出してくれる型のこと、色々種類がありますが、以下よく使うものを忘備録としてまとめました。

1. Record型

Record<Keys, Type>

プロパティのキーがKeys、プロパティの値がTypeのオブジェクト型を作るユーティリティ型

// サンプル
type StringNumber = Record<string, number>;

const value: StringNumber = { a: 1, b: 2, c: 3 };

Record型のメリットは柔軟性です。
動的なキーを持つオブジェクトや、プロパティが動的なオブジェクトなど複雑な型定義を行いたい時に便利です。

プロパティが決まっているオブジェクトの型定義であればtypeinterfaceで作ります。

Record型とObject型の違い、使い分けのポイント

キーの名前、数が不明で 動的
(APIレスポンスなど)
Record<K, T>
キーの名前や数が 固定・明確
(設計されたデータ構造)
Interface または type

2. Exclude型

Exclude<T, U>

ユニオン型TからUで指定した型を取り除いたユニオン型を返すユーティリティ型

// サンプル
type Grade = "A" | "B" | "C" | "D" | "E";

type PassGrade = Exclude<Grade, "E">;

// PassGradeは次の型になります。
type PassGrade = "A" | "B" | "C" | "D";

3. Pick型

Pick<T, Keys>

型TからKeysに指定したキーだけを含むオブジェクトの型を返すユーティリティ型

// サンプル
type User = {
  surname: string;
  middleName?: string;
  givenName: string;
  age: number;
  address?: string;
  nationality: string;
  createdAt: string;
  updatedAt: string;
};

type Person = Pick<User, "surname" | "middleName" | "givenName">;

// Personは次の型になります。
type Person = {
  surname: string;
  middleName?: string;
  givenName: string;
};
0
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
0
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?