Angular 角度)在声明时,是否有更好的方法初始化类中对象的值?
我想做的就是这样Angular 角度)在声明时,是否有更好的方法初始化类中对象的值?,angular,typescript,Angular,Typescript,我想做的就是这样 export class TestModel { item1: {title: 'specific title', content: string}; item2: {title: 'specific title', content: string}; } interface testInterface { title: string; content: string; } export class TestModel { item1
export class TestModel {
item1: {title: 'specific title', content: string};
item2: {title: 'specific title', content: string};
}
interface testInterface {
title: string;
content: string;
}
export class TestModel {
item1: testInterface ;
item2: testInterface ;
constructor() {
this.item1 = { title: 'specific titleA', content: '' };
this.item2 = { title: 'specific titleB', content: '' };
}
}
声明对象{title:string,value:string},并仅初始化title。内容的值将在声明后添加 但它不起作用。 所以我把它改成这样
export class TestModel {
item1: {title: 'specific title', content: string};
item2: {title: 'specific title', content: string};
}
interface testInterface {
title: string;
content: string;
}
export class TestModel {
item1: testInterface ;
item2: testInterface ;
constructor() {
this.item1 = { title: 'specific titleA', content: '' };
this.item2 = { title: 'specific titleB', content: '' };
}
}
我想在不使用构造函数()的情况下初始化title,以减少代码量。(如果可能,只初始化标题,而不初始化内容) 我试过了
item1:testInterface={title='特定titleA,content=''''}代码>
而且它也不起作用
有什么好的解决方案吗?您可以在字段声明中指定默认值,然后将Partial
对象传递给构造函数并合并它们:
interface TestInterface {
title: string;
content: string;
}
export class TestModel {
item1: TestInterface = {title: 'Default title', content: 'Default content'};
item2: TestInterface = {title: 'Default title', content: 'Default content'};
constructor(item1: Partial<TestInterface>, item2: Partial<TestInterface>) {
this.item1 = {...this.item1, ...item1};
this.item2 = {...this.item2, ...item2};
}
}
const x = new TestModel({title: 'Specific title 1'}, {content: 'Content 2'});
哇!谢谢我不知道部分对象。