LoginSignup
0
0

【Typescript】便利だけどたまにしか使わない忘れがちなユーティリティ型

Last updated at Posted at 2024-03-26

ユーティリティ型

そもそもユーティリティ型がなにかと言うと、型を別の型に変換してくれる型のことです。
たくさんありますが、私が最近よく遭遇したものを挙げてみます。

Record

RecordはプロパティのキーがKeysであり、プロパティの値がTypeであるオブジェクトの型を作るユーティリティ型です。

type Person = Record<"firstName" | "middleName" | "lastName", string>;
const person: Person = {
  firstName: "Robert",
  middleName: "Cecil",
  lastName: "Martin",
};

Exclude

Excludeは、ユニオン型TからUで指定した型を取り除いたユニオン型を返すユーティリティ型です。
名前通り、除外することができます。

type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "E">;

// 上のPassGradeは次の型と同じになります。

type PassGrade = "A" | "B" | "C" | "D";

Extract

Extractは、ユニオン型TからUで指定した型だけを抽出した型を返すユーティリティ型です。
Excludeとは逆ですね。名前が似ていてどっちがどっちかややこしいです。

type Grade = "A" | "B" | "C" | "D" | "E";
type FailGrade = Extract<Grade, "D" | "E">;
        
// type FailGrade = "D" | "E"

参考

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