mayuzu.me
← トップページに戻る

TypeScriptのユーティリティ型

#TypeScript

TypeScriptのユーティリティ型について、サバイバルTypeScriptを見ながらさらっていく。

サバイバルTypeScript ユーティリティ型 (utility type)

Required<T>

Required<T>は全てのプロパティを必須項目にする。

type Person = {
  name: string;
  age: number;
  gender?: "male" | "female" | "other";
};
type RequiredPerson = Required<Person>;

// プロパティ 'gender' は型 '{ name: string; age: number; }' にありませんが、型 'Required<Person>' では必須です。ts(2741)
const person: RequiredPerson = {
  name: "John",
  age: 30,
};

Personではgenderをoptionalにしているが、Requiredを使うことで必須の項目になることがわかる。

Readonly<T>

Readonly<T>は全てのプロパティを読み取り専用にする。

type Person = {
  name: string;
  age: number;
  gender?: "male" | "female" | "other";
  address: {
    city: string;
    country: string;
  };
};
type ReadonlyPerson = Readonly<Person>;

const person: ReadonlyPerson = {
  name: "John",
  age: 30,
  address: {
    city: "Tokyo",
    country: "Japan",
  },
};
// 読み取り専用プロパティであるため、'age' に代入することはできません。
person.age = 45;
//読み取り専用プロパティであるため、'address' に代入することはできません
person.address = {
  city: "Osaka",
  country: "Japan",
};
// 全てがReadonlyにはならず、オブジェクトがある場合は読み取り専用にはならない。
person.address.city = "Osaka"; // OK

Partial<T>

Partial<T>は全てのプロパティをオプショナルにする。

type Person = {
  name: string;
  age: number;
  gender?: "male" | "female" | "other";
  address: {
    city: string;
    country: string;
  };
};
type PartialPerson = Partial<Person>;

// ageは省略可能
const withoutAge: PartialPerson = {
  name: "John",
  address: {
    city: "Tokyo",
    country: "Japan",
  },
};
// objectの中は省略可能にならない
const withoutCountry: PartialPerson = {
  name: "John",
  gender: "male",
  address: { // プロパティ 'country' は型 '{ city: string; }' にありませんが、型 '{ city: string; country: string; }' では必須です。
    city: "Tokyo",
  },
};

Record<Keys, Type>

Record<Keys, Type>はプロパティのキーがKeys、値がTypeのオブジェクトを作成する。

type StringNumber = Record<string, number>;
const value: StringNumber = { hoge: 1, fuga: 2 };
console.log(value.hoge); // 1

type NumberString = Record<number, string>;
const value2: NumberString = { 1: "hoge", 2: "fuga" };
console.log(value2[1]); // "hoge"

type HogeFuga = Record<"hoge" | "fuga", string>;
const value3: HogeFuga = { hoge: "hoge", fuga: "fuga" };
console.log(value3.hoge); // "hoge"

Pick<T, Keys>

Pick<T, Keys>TからKeysに指定したキーだけを含むオブジェクトの型を作る。

type Person = {
  name: string;
  age: number;
  gender?: "male" | "female" | "other";
  address: {
    city: string;
    country: string;
  };
};

type PickPerson = Pick<Person, "name" | "age">;
const person: PickPerson = {
  name: "John",
  age: 30,
};

Omit<T, Keys>

Omit<T, Keys>TからKeysに指定したキーを除いたオブジェクトの型を作る。Pickの逆のイメージ。

type Person = {
  name: string;
  age: number;
  gender?: "male" | "female" | "other";
  address: {
    city: string;
    country: string;
  };
};

type OmitPerson = Omit<Person, "gender" | "address">;
const person: OmitPerson = {
  name: "John",
  age: 30,
};

Omitの注意点として、以下のようにKeysTに存在しないキー名を入れてもエラーにならない。

type OmitPerson = Omit<Person, "gender" | "adddddressss">;