我正在尝试初始化具有函数的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' }]
};
是否有更简单的方法来初始化它?
答案 0 :(得分: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' }]
);