TypeScript继承-如何向现有属性添加一些字段

时间:2018-09-25 11:36:10

标签: typescript

我用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类中拥有CarElement,并作为CarElement属性来访问它。

但是我不能仅仅将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结构完整,保持对象结构以及以某种方式扩展已经存在的类属性?

1 个答案:

答案 0 :(得分:0)

以下为我工作:

export class CarElement {
  constructor(
    public id: number,
    public type: string,
    public options: CarElementOptions
  ) {}
}

export class CarElementOptions {
    constructor(public carPart: string) {}
}


export class SteeringWheel extends CarElement {
  constructor(
    public id: number,
    public type: string,
    public options: SteeringWheelOptions
  ) {
    super(id, type);
  }
}

export class SteeringWheelOptions extends CarElementOptions{
    constructor(public carPart: string, public airbag: boolean){
       super(carPart);
    }
}

export class Wheel extends CarElement {
  constructor(
    public id: number,
    public type: string,
    public options: WheelOptions
  ) {
    super(id, type);
  }
}

export class WheelOptions extends CarElementOptions{
    constructor(
       public carPart: string, 
       public radius: number,
       public typeType: string,
       public position: string
    ){
       super(carPart);
    }
}