当サイトは、アフィリエイト広告を利用しています
typescript における分割代入をまとめる
配列やオブジェクトを変数に分割して代入することができる
// 配列を作成const arr = Array.of(1, 2, 3);// 分割代入const [val1,val2] = ...arrconsole.log(val1)console.log(val2)// ログ// 1// 2
constで宣言した場合は再代入できないが
letの場合はできる
// 配列を作成const arr = Array.of(1, 2, 3, 4, 5);// 分割代入let [val1,val2] = arrval1 = 2000console.log(val1)console.log(val2)// ログ// 2000// 2
typeScriptでは型推論が働く場合がある
// パターン①// 配列を作成const arr1 = [1, "abc", true]// 分割代入let [num1, str1, bool1] = arr1// 型推論は働かないためエラー発生しないnum1 = 'moji'str1 = 111bool1 = false// パターン②// 型を指定してタプルを設定const arr2: [number, string, boolean] = [1, "abc", true]let [num2, str2, bool2] = arr2// 型推論が働くnum2 = 'moji' //コンパイルエラーstr2 = 111 //コンパイルエラーbool2 = false// パターン③// 右辺の配列リテラルは TypeScript ではタプル型とされるlet [num, str, bool] = [1, "abc", true]// 型推論が働くnum = 'moji' //コンパイルエラーstr = 111 //コンパイルエラーbool = false
いつくかサンプル実装してみる
レスト構文を使うとあまりをまとめて代入できる
// 配列を作成const arr = Array.of(1, 2, 3, 4, 5);// 分割代入でレスト構文を使うlet [val1, val2,...rest] = arr;console.log(val1);console.log(val2);console.log(rest);// ログ// 1// 2// (3) [3, 4, 5]
// 配列を作成const arr = Array.of(1, 2, 3, 4, 5);// 分割代入で指定して取得let [val1, , , , val5] = arr;console.log(val1);console.log(val5);// ログ// 1// 5
オブジェクトの中から必要な属性だけを抽出して変数に代入することができる。
type User = {id: number,name:string,age?:number};const user:User = { id: 1, name: "hogehoge" }// idとnameだけ分割代入で取得するconst {id,name} = userconsole.table(id)console.log(name)// ログ// 1// hogehoge
デフォルト値を設定することできる
// typeを定義type User = {id: number;name?: string;age?: number;};// オブジェクト作成// idしか設定しないconst user: User = { id: 1 };// idとnameだけ分割代入で取得する// nameにはデフォルト値を設定const { id, name = "defoult"} = user;console.table(id);console.log(name);// ログ// 1// defoult
分割代入の左辺には型アノテーションを指定できる
型アノテーションは個別、type,interfaceのどれでも設定可能。
export * from "./add";// typeを定義type User = {id: number;name?: string;age?: number;};type User2 = {id2: number;name2?: string;};// オブジェクト作成const user: User = { id: 1 };const user2: User2 = { id2: 2 };// idとnameだけ分割代入で取得する// 型アノテーションを個別で設定const { id, name = "defoult"}:{id:number,name?:string} = user;// 型アノテーションをtypeで設定(interfaceでも可)const { id2, name2 = "defoult2"}:User2 = user2;console.table(id);console.log(name);console.table(id2);console.log(name2);// ログ// 1// defoult// 2// defoult2
分割代入では別名を付けることも可能
// typeを定義type User = {id: number;name: string;age?: number;};// オブジェクト作成const user: User = { id: 1, name: "hogehoge" };// idとnameだけ分割代入で取得するconst { id, name: firstName }: { id: number; name?: string } = user;console.table(id);console.log(firstName);// ログ// 1// hogehoge
型は分割代入後も保持される。
// オブジェクトを定義let user: {id:number,name:string,age:number} = {id: 1,name: "hoge",age: 20};// 分割代入let {id,age} = user// 分割代入後も型は保持しているid = 'aaa' //エラー
いつくかサンプル実装してみる
変数宣言と代入を別の行に分ける場合は少し書き方が異なる
export * from "./add";// 空オブジェクトの型type EmptyObject = { [key: string]: any };// オブジェクトを定義let user: EmptyObject = {id: 1,name: "hhoge",age: 20};// 分割代入用の変数を定義let id: number, age: number;// 分割代入// ()で囲まないとエラーになる({id,age} = user)console.table(id);console.log(age);// ログ// 1// 20
分割代入側でも同じように階層を作ってやる必要がある。
// オブジェクトを定義const user = {id: 1,detail: {name: "hoge",age: 21}};// 階層別分割代入するconst {detail: { name }} = user;console.log(name)
引数に分割代入を使用する事ができる
// 関数を定義// 分割代入とレスト構文で受け取るconst func = ({id,name,...rest})=>{console.log(id)console.log(name)console.log(rest.age)}// typeを定義type User = {id: number,name:string,age?:number};// オブジェクト作成const user:User = { id: 1, name: "hogehoge",age:21 }// 関数呼出しfunc(user)// 実行結果// 1// hogehoge// 21
デフォルト値を設定してやると引数なしで呼び出すこともできる
デフォルト値を設定しない場合はエラーになる
/// 関数を定義// デフォルト値を設定(まとめて設定)const func = ({id,name}={id:0,name:"defoult"})=>{console.log(id)console.log(name)}// デフォルト値を設定(個別で設定)const func2 = ({id=99,name="defoult99"}={})=>{console.log(id)console.log(name)}// 関数呼出しfunc()func2()// ログ// 0// defoult// 99// defoult99
下記の記事を参考してまとめさせて頂きました。 TypeScript と JSX の基礎文法を習得する
今さら分割代入知らないなんて言えないので TypeScript でこっそり勉強する
JavaScript: オブジェクトの分割代入とスプレッド構文を使ってみる