分割代入はオブジェクトからプロパティを取り出して別個の変数に代入することができる構文です。
たとえばcountryという”name”と”code”のプロパティをもつオブジェクトがあるとします。
このとき”code”プロパティの値だけを別の変数に格納したい場合に分割代入が活躍します。
const country = { name:"Japan", code:"JPN" } let { code } = country; console.log( code ); // "JPN"
この分割代入の仕組みは関数の引数にも適応することができます。
function getCode({code}){ return code; } console.log( getCode(country) ); // "JPN"
この例ではgetCodeの引数にオブジェクトを渡すと、その中のcodeプロパティの値だけを抽出して関数内の処理に移ります。
ただし、このままだと型がanyなのでTypeScriptではエラーが発生します。
“binding element ‘code’ implicitly has an ‘any’ type”
では引数に分割代入を用いた場合、どのように型を指定すればよいのでしょうか?
分割代入の型指定
分割代入を引数に取った場合の型指定は以下のように指定します。
function getCode( {code}:{code:string} ){ return code; } console.log( getCode(country) ); // "JPN"
interfaceをつかった型指定
もちろんinterfaceをつかって型指定することも可能です。
interfaceを使用する場合は以下のように指定します。
interface CountryCode { code : string; } function getCode({code}:CountryCode){ return code; } console.log( getCode(country) ); // "JPN"
分割代入のデフォルト値指定
分割代入を引数に取った場合のデフォルト値は以下のように指定します。
interface CountryCode { code : string; } function getCode({code}:CountryCode = {code:"XXX"}){ return code; } console.log( getCode() ); // "XXX"