【发布时间】:2021-02-14 13:34:01
【问题描述】:
假设我有两个接口,它们有两个相同的成员 id 和 name:
export interface InterfaceA {
id: number;
name: string;
//some other members
}
export interface InterfaceB {
id: number;
name: string;
//some other members
}
我想收集两种类型的元素来填充一些组合框。 我需要每个元素的 id、名称和类型,所以我做了以下课程
export class AssignableDevice {
id: number;
name: string;
type: string;
constructor(device: InterfaceA | InterfaceB) {
this.id = device.id;
this.name = device.name;
this.type = typeof device; //still returns "object"
}
}
// in onInit method :
ngOnInit() {
super.ngOnInit();
this.dataService.getInterfaceA().subscribe((data) => {
data.forEach((element) => this.devices.push(new AssignableDevice(element as InterfaceA)));
});
this.dataService.getInterfaceB().subscribe((data) => {
data.forEach((element) => this.devices.push(new AssignableDevice(element as InterfaceB)));
})
}
但问题是我总是在“AssignableDevice”类构造函数中得到“对象”,我不知道为什么会这样。 我可以通过使用一些枚举来实现我的目标,但我想知道为什么这个解决方案不起作用,以及如何实现这一点。 我宁愿不对 InterfaceA 或 InterfaceB 进行任何更改。
【问题讨论】:
-
你想用这个类型做什么?您还没有显示
this.type在任何地方使用。如果我们知道您想用它做什么,我们就能更好地帮助您。 -
我想将“type”与其他数据一起发送到后端,并在此基础上确定我应该在哪个表中插入记录。
标签: angular typescript casting type-conversion type-assertion