👓

【TypeScript】オブジェクトの分割代入 (destructuring assignment)

に公開

はじめに

はじめまして!分割代入についてまとめていきたいと思います。
分割代入 (destructuring assignment) とは、オブジェクトや配列から必要な値を取り出し、変数に代入する構文です。

基本的な例

// User 型を定義
type User = {
  id: number;
  firstName: string;
  age: number;
};

const user: User = { id: 1, firstName: "Alice", age: 25 };

// 通常の代入
//const id = user.id
//const firstName = user.firstName;

// 分割代入
const { id, firstName } = user;

console.log(id, firstName); // 1, "Alice"

別名の利用例

// User 型を定義
type User = {
  id: number;
  name: string;
};

const user: User = { id: 1, name: "Alice" };

// 分割代入しつつ別名を付ける
const { name: userName } = user;

console.log(userName); // "Alice"

ポイント
プロパティ名と異なる変数名を使いたい場合は別名を指定できます。

デフォルト値の指定

// User 型を定義
type User = {
  id: number;
  username?: string; // プロパティが省略される可能性があるので ? をつける
};

const user: User = { id: 1 };

const { username = "Unknown" } = user;

console.log(username); // "Unknown"

ポイント

  • プロパティが undefined の場合に備えてデフォルト値を設定できます。
  • デフォルト値は プロパティが undefined のときのみ適用されます。

ネストされたオブジェクトの分割代入

// 型を定義
type Profile = {
  nickname?: string; 
  age?: number;
};

type User = {
  id: number;
  profile?: Profile; 
};

const user: User = {
  id: 1,
  profile: { nickname: "alice123", age: 25 },
};

// ネスト分割代入
const { profile: { nickname = "Anonymous", age = 0 } = {} } = user;

console.log(nickname, age); // "alice123", 25

const user2: User = { id: 2 };
const { profile: { nickname: nick2 = "Anonymous", age: age2 = 0 } = {} } = user2;

console.log(nick2, age2); // "Anonymous", 0

ポイント
入れ子になったオブジェクトからも直接取り出せます。

関数の引数での利用

type User = {
  id: number;
  name: string;
  age: number;
};

function greet({ name, age }: User) {
  console.log(`Hello ${name}, you are ${age} years old.`);
}

greet({ id: 1, name: "Alice", age: 25 });

ポイント
関数のパラメータで分割代入を使うと、呼び出し側で渡されたオブジェクトから必要な値だけを直接受け取れます。

残余プロパティ

type User = {
  id: number;
  name: string;
  age: number;
};

// 最も実用的で読みやすい方法
type UserDetails = Omit<User, 'id'>;

const user: User = { id: 1, name: "Alice", age: 25 };
const { id, ...rest } = user;

// 必要に応じて型アサーションまたは別変数で型を明示
const userDetails: UserDetails = rest;

console.log(id);          // 1 (型: number)
console.log(userDetails); // { name: "Alice", age: 25 } (型: UserDetails)

ポイント
分割代入で使われなかった残りのプロパティをまとめて受け取ることも可能です。

オブジェクトの分割代入を使う理由

  1. コードが短く・読みやすくなる
    const name = user.name; を何度も書かずに済む。
  2. 必要なものだけ取り出せる
    大きなオブジェクトから特定のプロパティだけを簡単に利用できる。
  3. 関数の引数を整理できる
    複数のプロパティを持つオブジェクトを渡すとき、必要なプロパティだけを直接受け取れる。
  4. ネスト構造に素早くアクセスできる
    入れ子のオブジェクトから直接プロパティを取り出し、アクセスを簡潔にできる。

Discussion