15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptで名前付き引数のようなものを使う

Posted at

TypeScript1.8での動作です。

// groupのデフォルト引数を指定 ageに関しては入力自由
function Idol({group = "Dempagumi.inc", name, age} : {group?: string, name: string, age?: number}){
    console.log(group, name, age)
}

Idol({name: "Yumemi Nemu"});  // groupはデフォルト値を使用 年齢はundefined
Idol({name: "Fujisaki Ayane", age: 20});  // groupはデフォルト値を使用 年齢を明示的に指定
Idol({group: "Momoiro Clover Z", name: "Tamai Shiori", age: 20});  // groupを明示的に指定

/*
Result
  Dempagumi.inc Yumemi Nemu undefined
  Dempagumi.inc Fujisaki Ayane 20
  Momoiro Clover Z Tamai Shiori 20
*/

ES6でも使用されるオブジェクトを変数に展開する仕組みdestructuringを使って実現しています。変換後のJavaScriptは以下のとおりです。

function Idol(_ref) {
    var _ref$group = _ref.group;
    var group = _ref$group === undefined ? "Dempagumi.inc" : _ref$group;
    var name = _ref.name;
    var age = _ref.age;

    console.log(group, name, age);
}
Idol({ name: "Yumemi Nemu" });
Idol({ name: "Fujisaki Ayane", age: 20 });
Idol({ group: "Momoiro Clover Z", name: "Tamai Shiori", age: 20 });

デフォルト値を受ける部分の型は名前に?を付けてオプションのフィールドとして設定します。

              /*    変数名とデフォルト値を指定    */   /*   受け取る変数のシグネチャ   */
function Idol({group = "Dempagumi.inc", name, age} : {group?: string, name: string, age?: number}){
15
9
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
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?