首页 > 解决方案 > TypeScript 类型继承:如何将具有父类型的变量分配给具有子类型的变量

问题描述

我创建了两种类型

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

现在我有两个变量A: GenericTypeand B: SpecificType,现在我想分配 to 的所有值AB另外,我想分配valueto B。我应该如何实现这一点,我不想遍历A's all 属性并手动将其分配给B's all 属性。

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';

标签: typescript

解决方案


不能这样做:

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';

但是你可以这样做:

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

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

您无法分配给varAvarB因为varA没有value,但您可以使用运算符将​​所有内容全部分配spread


推荐阅读