2016-01-13 7 views
5

クラスのコンストラクタの引数としてオブジェクトを渡したいとします。オプションオブジェクトの一部のキーはオプションです。options引数のオプションパラメータのデフォルト値

typescriptで以下のことを行うのは、より寛容な方法がありますか?ありがとう

class Car { 
    color: number; 
    numberOfWheels: number; 

    constructor (options: {color: number, numberOfWheels?: number}) { 
     options.numberOfWheels |= 4; 

     this.color = options.color; 
     this.numberOfWheels = options.numberOfWheels; 
    } 
} 

答えて

4

if (options.numberOfWheels === void 0) { options.numberOfWheels = 4; }を代わりに使用してください。 (それ以外の場合は0またはNaN ...も4となります)

実際にあなたがすることは、実際にはかなり巧妙であり、あなたができることは最高です。そのような 物事は動作しません:あなたはこのためdestructuringを使用することができます

constructor (options: {color: number, numberOfWheels?: number} = {color: options.color}) 
2

:また

class Car { 
    color: number; 
    numberOfWheels: number; 

    constructor ({color, numberOfWheels = 4}: {color: number, numberOfWheels?: number}) { 
     this.color = color; 
     this.numberOfWheels = numberOfWheels; 
    } 
} 

...

constructor (options: {color: number, numberOfWheels?: number}) { 
    let {color, numberOfWheels = 4} = options; 

    this.color = color; 
    this.numberOfWheels = numberOfWheels; 
} 
0

を私は活字最新と厩舎のバージョンを使用していますVSCodeで2017年6月現在。

以下のappraochを使用して、オプションのパラメータとデフォルト値を達成できます。

export class Searcher { 
    createLog(message: string = "Default: No Message!") { 
    console.log(message); 
    } 
} 

Optional and Default valued parameters in TypeScriptについて学ぶための参考資料のリンク。

こちらがお役に立てば幸いです。

関連する問題