2
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?

分割代入の省略記法について

Posted at

はじめに

TypeScript のコードで分割代入を使用したときに、初めて知った書き方があったのでまとめます。

今回初めて知ったのは、カンマの後に変数名を記述する以下のような書き方です。

const [, second] = array;
const entry = items.find(([, value]) => value === target);

基本の分割代入

まず、配列から値を取り出す方法は以下のように記述します。

const colors = ["red", "yellow", "blue"];

// 基本的な書き方
const second = colors[1];   // yellow

// 分割代入
const [first, second, third] = colors;
console.log(second); // yellow

そして、配列から部分的な要素を取得したいときは不要な要素を カンマでスキップする ことができます。

const fruits = ["apple", "banana", "melon"];

// 2番目だけ欲しい → 1番目をスキップ
const [, second] = fruits;
console.log(second); // banana

// 3番目だけ欲しい → 1,2番目をスキップ
const [, , third] = fruits;
console.log(third); // melon

カンマ( , )で位置を示し、変数名を省略するとその要素をスキップできる

実践的な使用例

Object.entries() との組み合わせ

const categories = {
  '飲料': 'beverages',
  'お菓子': 'snacks'
};

// Object.entries() で取得できる形式
// [['飲料', 'beverages'], ['お菓子', 'snacks']]

// valueで検索したい場合
const targetTag = 'beverages';

// 読みにくい
const entry = Object.entries(categories).find(entry => entry[1] === targetTag);

// keyはスキップ、tagのみ使用
const entry = Object.entries(categories).find(([, tag]) => tag === targetTag);                                              

配列メソッドとの組み合わせ

const userEntries = [
  ['user1', { name: '田中', age: 25 }],
  ['user2', { name: '佐藤', age: 30 }]
];

// IDは不要、ユーザー情報だけ欲しい
const users = userEntries.map(([, userInfo]) => userInfo);
// [{ name: '田中', age: 25 }, { name: '佐藤', age: 30 }]

関数での活用する場合

// Xは不要、Yだけ使いたい
function getHeight([, y]: [number, number]) {
  return y;
}

console.log(getHeight([10, 20])); // 20

予期しない undefined の発生を防ぐ

// エラーが発生
const [a, b, c] = [1, 2]; // c は undefined

// デフォルト値の使用でエラー回避
const [a, b, c = 0] = [1, 2]; // c は 0

まとめ

分割代入の [ , value] の記法については、Object.entries() Object.map() でよく使用するので覚えておきたいです。

参考サイト

2
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
2
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?