Change the class of another class' instance

1.5k views Asked by At

I have a Angular 4 Typescript app that have multiple types of objects defined by classes that have different type properties, as below:

export class Fruit {
  name: string;
  type: string;

  constructor(columnName: string) {
    this.name = columnName;
  }
}

export class Apple extends Fruit {
  /* additional properties */

 constructor(name: string) {
    super(name);
  }

  get type(): string {
    return 'apple';
  }
}

export class Orange extends Fruit {
  /* additional properties different from Apple */

 constructor(name: string) {
    super(name);
  }

  get type(): string {
    return 'Orange';
  }
}

These objects belong to a basket object in an array member, like fruits in a basket. I would like to be able to dynamically set the kind of fruit via a dropdown in a form. Every time I do that, I get:

ERROR TypeError: Cannot set property type of [object Object] which has only a getter

I'm new to Typescript and I reckon I'm doing an advance thing already, but this is something required for a project I'm doing.


EDIT:

I use ng-formly to generate my form elements. The relevant html looks like this:

<form class="formly" role="form" [formGroup]="fruitBasket" novalidate>
  <div formArrayName="fruits">
    <div *ngFor="let control of fruitBasketForm.controls.fruits.controls; let i = index">
      <formly-form
        [model]="fruitBasket.fruits[i]"
        [fields]="fruitFields[i]"
        *ngIf="i === currFruitIndex">
      </formly-form>
    </div>
  </div>
</form>
1

There are 1 answers

1
eko On BEST ANSWER

In this example your super class should have a setter since there is a name collision in your type field

export class Fruit {
  name: string;
  type: string;

  constructor(columnName: string) {
    this.name = columnName;
  }

  set type(type){
    this.type = type;
  }
}

But the real usage of inheritance is that every object should know which class they belong to and use the method in their classes. If you are depending on a type property in an inheritance architecture you are not really using the full power of inheritance.