TypeScript Type Inheritance : How to assign variable with parent type to the variable with child type

Viewed 1211

I have created two types

export class GenericType {
  public id: string;
  public property: string;
  public name: string;
}
export class SpecificType extends GenericType {
  public value: string;
}

Now I have two variable A: GenericType and B: SpecificType, now I want to assign all the values of A to B, and additionally, I want to assign value to B. How should I achieve this, I don't want to loop through A's all property and manually assign it to B's all property.

let varA: GenericType = {
  id: '123',
  property: 'exmple',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
varB = varA;  <----- not allowing to assign.
varB.value = 'new value';
2 Answers

You cannot do this:

let varA: GenericType = {
  id: '123',
  property: 'exmple',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
varB = varA;  <----- not allowing to assign.
varB.value = 'new value';

But you can do this:

let varA: GenericType = {
  id: '123',
  property: 'exmple',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
// Difference here:
varB = { ...varA, value: 'new value' }

You cannot assign varA to varB because varA does not have value, but you can assign everything altogether using the spread operator.

You're not allowed to assign it because the property value does not exist in the GenericType class, to circumvent this you can do a type assertion to SpecificType:

let varB: SpecificType = new SpecificType();
varB = varA as SpecificType; // Allowed to assign now.
varB.value = 'new value';
Related