Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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}){
sakura_internet
さくらレンタルサーバ、さくらのVPS、 さくらのクラウド、さくらの専用サーバなどのインターネットサービス・ITプラットフォームを提供しています。
https://www.sakura.ad.jp/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした