2017-04-10 213 views
6

定義爲默認設置可選的構造函數參數是否有可能有可選的構造函數參數的默認值,這樣如何打字稿

export class Test { 
    constructor(private foo?: string="foo", private bar?: string="bar") {} 
} 

這給了我下面的錯誤:

參數不能有問號和初始化程序。

我想喜歡

x = new Test();    // x.foo === 'foo'    
x = new Test('foo1');   // x.foo === 'foo1' 
x = new Test('foo1', 'bar1'); 

什麼是正確的打字稿的方式來實現這一目標創建實例?

+1

難道你嘗試'構造函數(private foo?foo:string =「foo」,private bar?bar:string =「bar」){}'? – Feathercrown

回答

14

其中有一個默認值的參數是通過定義可選的,因爲stated in the docs

Default-initialized parameters that come after all required parameters are treated as optional, and just like optional parameters, can be omitted when calling their respective function

它是構造相同,因爲它是對等功能,讓你的情況:

export class Test { 
    constructor(private foo: string = "foo", private bar: string = "bar") {} 
}