Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@kamijin_fanta

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

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}){
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
8
Help us understand the problem. What are the problem?