我用 TypeScript 编写 Angular 应用程序,现在我被困在尝试实现类层次结构来管理从后端获取的 JSON 对象。
假设我得到Car了包含几个元素的对象。JSON对象看起来像
{
"id": 19,
"title": "Big Car",
"status": "running",
"elements": [{
"id": 697,
"type": "steering wheel",
"options": {
"carPart": "steering",
"airbag": true
}
}, {
"id": 700,
"type": "wheel",
"options": {
"carPart": "wheels",
"radius": 16,
"tyreType": "winter",
"position": "front left"
}
}]
}
以前我没有element.options.carPart财产,所以我的课就像
export class Car{
constructor(
public id: number,
public title: string,
public stauts: string,
public elements: CarElement[]
) {}
}
export class CarElement {
constructor(
public id: number,
public type: string
) {}
}
export class SteeringWheel extends CarElement {
constructor(
public id: number,
public type: string,
public options: { airbag: boolean }
) {
super(id, type);
}
}
export class Wheel extends CarElement {
constructor(
public id: number,
public type: string,
public options: { radius: number, tyreType: string, position: string }
) {
super(id, type);
}
}
现在我需要上课,并将其作为element.options.carPart财产访问。CarElementCarElement
但我不能只将 CarElement 更改为
export class CarElement {
constructor(
public id: number,
public type: string,
public options: { carPart: string }
) {}
}
当然,我得到error TS2415: Class 'Wheel' incorrectly extends base class 'carElement'. Types of property 'options' are incompatible.
所以,我的问题是 - 是否有任何选项可以保持 JSON 结构完整,保持对象结构,并以某种方式扩展已经存在的类属性?