[TypeScript]ユーティリティ型
Partial<T>
プロパティをオプショナルにする
interface User { id: number; name: string; age: number; } type PartialUser = Partial<User>; const user: PartialUser = { name: "Taro" }; // OK(id, age なしでもOK)
Required<T>
プロパティを必須にする
interface User { id: number; name?: string; age?: number; } type RequiredUser = Required<User>; const user: RequiredUser = { id: 1, name: "Taro", age: 25 }; // OK // const user2: RequiredUser = { id: 1 }; // エラー(name, age が必須)
Readonly<T>
プロパティを読み取り専用にする
interface User { id: number; name: string; } const user: Readonly<User> = { id: 1, name: "Taro" }; // user.name = "Jiro"; // エラー(再代入不可)
Pick<T, K>
特定のプロパティのみを取り出す
interface User { id: number; name: string; age: number; } type PickedUser = Pick<User, "id" | "name">; const user: PickedUser = { id: 1, name: "Taro" }; // OK(ageなし)
Omit<T, K>
特定のプロパティを除外する
interface User { id: number; name: string; age: number; } type OmittedUser = Omit<User, "age">; const user: OmittedUser = { id: 1, name: "Taro" }; // OK(ageなし)
Record<K, T>
オブジェクトのキーと値の型を指定
キー(K)の型と値(T)の型を固定できる。
type UserRoles = Record<"admin" | "user" | "guest", number>; const roles: UserRoles = { admin: 1, user: 2, guest: 3, };
Extract<T, U>
Tの中からUに一致する型を抽出
type Status = "active" | "inactive" | "banned"; type ActiveStatus = Extract<Status, "active" | "banned">; const status1: ActiveStatus = "active"; // OK const status2: ActiveStatus = "banned"; // OK // const status3: ActiveStatus = "inactive"; // エラー(除外されている)
Exclude<T, U>
Tの中からUに一致する型を除外
type Status = "active" | "inactive" | "banned"; type InactiveStatus = Exclude<Status, "active">; const status1: InactiveStatus = "inactive"; // OK const status2: InactiveStatus = "banned"; // OK // const status3: InactiveStatus = "active"; // エラー(除外されている)
NonNullable<T>
nullとundefinedを除外
type Data = string | number | null | undefined; type NonNullableData = NonNullable<Data>; const value1: NonNullableData = "hello"; // OK const value2: NonNullableData = 42; // OK // const value3: NonNullableData = null; // エラー // const value4: NonNullableData = undefined; // エラー
ReturnType<T>
関数の戻り値の型を取得
function getUser() { return { id: 1, name: "Taro" }; } type UserType = ReturnType<typeof getUser>; const user: UserType = { id: 2, name: "Jiro" }; // OK
ユーティリティ型 | 説明 |
---|---|
Partial<T> | すべてのプロパティをオプショナルにする |
Required<T> | すべてのプロパティを必須にする |
Readonly<T> | すべてのプロパティを変更不可にする |
Pick<T, K> | 指定したプロパティのみ抽出 |
Omit<T, K> | 指定したプロパティを除外 |
Record<K, T> | キー K に対して値 T を割り当てる |
Extract<T, U> | U に一致する型のみを抽出 |
Exclude<T, U> | U に一致する型を除外 |
NonNullable<T> | null と undefined を除外 |
ReturnType<T> | 関数の戻り値の型を取得 |