TypeScript - 分割代入(Destructuring assignment)

公開日:2019-02-08 更新日:2019-05-14

1. 概要

配列やオブジェクトの値を個別の変数に一括で代入します。

let [変数1, 変数2, ・・・] = [値1, 値2, ・・・];

let {キー1, キー2, ・・・} = [キー1:値1, キー2:値2, ・・・];

2.1 サンプル - 配列リテラル

let [a, b, c] = [1, 2, 3, 4, 5];
console.log(a); //1
console.log(b); //2
console.log(c); //3

//ビルドエラー
//let [d, e, f] = [1];

2.2 サンプル - オブジェクトリテラル

let { a, b, c } = { a: 1, b: 2, c: 3 };
console.log(a); //1
console.log(b); //2
console.log(c); //3

//ビルドエラー
//let { d, e, f } = { d: 1};