2017-07-31 85 views
0

我想初始化一個類中有函數的類,我不想每次複製方法定義來初始化一個對象。我不喜歡大量的構造,這是我的課Typescript有沒有更簡單的方法來初始化?

export class ISelectInputOption { 

    title: string; 
    subTitle: string; 
    mode: string; 
    options: Array<EnumOption>; 
    resolveName(id: number): string { 

     var option = this.options.filter(option => option.id == id); 

     if (option && option.length > 0) { 
      return option[0].name; 
     } 
     return ''; 
    } 
}; 

我有被初始化這些我想這樣做一個單獨的文件,但這是不允許的:

priceTypeOptions: ISelectInputOption = = new ISelectInputOption() 
{ 
    title: 'Payment Frequencies', 
    subTitle: 'Select the frequency', 
    mode: 'md', 
    options: [{ id: 0, name: 'None', description: 'No Option' }] 
}; 

有一個更簡單的方法來初始化這個?

回答

2

您可以使用Object.assign創建類似的初始化模式:

let priceTypeOptions: ISelectInputOption = Object.assign(new ISelectInputOption, { 
    title: 'Payment Frequencies', 
    subTitle: 'Select the frequency', 
    mode: 'md', 
    options: [{ id: 0, name: 'None', description: 'No Option' }] 
}); 

你可以嘗試另一種選擇是使用parameter properties

類定義更改爲:

export class ISelectInputOption { 

    constructor(
     public title: string, 
     public subTitle: string, 
     public mode: string, 
     public options: Array<EnumOption> 
    ) { 

    } 
    // ... 
}; 

並初始化它:

let priceTypeOptions: ISelectInputOption = new ISelectInputOption(
    'Payment Frequencies', 
    'Select the frequency', 
    'md', 
    [{ id: 0, name: 'None', description: 'No Option' }] 
); 
+0

對象分配是完美的 –

相關問題