我确信我在这里只是很愚蠢,但我有这个模型:
import { Brand } from './brand';
import { Plan } from './plan';
import { Venue } from './venue';
export class Subscription {
id: number;
brandId: number;
planId: number;
venueId: number;
state: number;
startDate: string;
endDate: string;
rolling: boolean;
overridePlan: boolean;
productCount: number;
price: number;
termsAgreed: boolean;
brand?: Brand;
plan?: Plan;
venue?: Venue;
get stateName(): string {
switch (this.state) {
case 0:
return 'Reserved';
case 1:
return 'Pending';
case 2:
return 'Active';
case 3:
return 'Cancelled';
case 4:
return 'Expired';
default:
return 'Unknown';
}
}
}
正如您所看到的,我使用getter来显示stateName。问题是,当我试图创建一个新模型时:
const model: Subscription = {
id: 0,
brandId: 0,
planId: 0,
venueId: 0,
state: 0,
startDate: '',
endDate: '',
rolling: true,
overridePlan: false,
termsAgreed: false,
price: 0,
productCount: 0,
};
它抱怨我没有为stateName设置值。我认为,因为这是一个getter,所以不需要设置?
错误如下:
类型"{id:number;brandId:number;planId:number;venueId:number;state:number;startDate:string;endDate:string;rolling:true;overridePlan:false;termsAgreed:虚假;价格:数字;productCount:number;}'但在类型"Subscription"中是必需的。
我真的必须指定它吗?
您没有创建Subscription对象的实例,因此该类上的任何getter或setter都不会出现在您的新实例中。
我们使用object.assign()
执行此任务。大致如下:
const model: Subscription = Object.assign(new Subscription(), {
id: 0,
brandId: 0,
planId: 0,
venueId: 0,
state: 0,
startDate: '',
endDate: '',
rolling: true,
overridePlan: false,
termsAgreed: false,
price: 0,
productCount: 0,
});
Subscription {
id: number;
brandId: number;
planId: number;
venueId: number;
state: number;
startDate: string;
endDate: string;
rolling: boolean;
overridePlan: boolean;
productCount: number;
price: number;
termsAgreed: boolean;
brand?: Brand;
plan?: Plan;
venue?: Venue;
stateName: string;
要使您的案例工作,您需要使用new
关键字实例化类,然后将值分配给属性:
const model = new Subscription();
model.id = 0;
...