typescript - TypeScript 类型继承:如何将具有父类型的变量分配给具有子类型的变量
问题描述
我创建了两种类型
export class GenericType {
public id: string;
public property: string;
public name: string;
}
export class SpecificType extends GenericType {
public value: string;
}
现在我有两个变量A: GenericType
and B: SpecificType
,现在我想分配 to 的所有值A
,B
另外,我想分配value
to 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';
解决方案
你不能这样做:
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' }
您无法分配给varA
,varB
因为varA
没有value
,但您可以使用运算符将所有内容全部分配spread
。
推荐阅读
- node.js - 错误:传入的参数必须是 12 字节的单个字符串或 ID 错误的 24 个十六进制字符的字符串
- javascript - 使用自定义滚动条模拟 Chrome 滚动条 - 禁用滚动条按钮上的悬停事件
- database - 用 Camel 在桌子上听插入
- python - 如何正确让 Flask 在 Heroku 的后台运行线程任务?
- python - 使用条件删除数据框中的行
- javascript - 如何在轮播中显示纵向和横向图像?
- r - 在 R 中使用 sapply 时如何保留列表的元素名称?
- sql-server - SQL 2014 等效于 string_agg 返回整数值
- sorting - 如何根据另一列计算唯一或最后一次出现的重复值?
- java - 继承枚举的子类:ClassNotDefinedError