假设我有两个接口,它们有两个相同的成员 id 和名称:
export interface InterfaceA {
id: number;
name: string;
//some other members
}
export interface InterfaceB {
id: number;
name: string;
//some other members
}
Run Code Online (Sandbox Code Playgroud)
我想获取这两种类型的元素的集合来填充一些组合框。我需要每个元素的 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) => { …
Run Code Online (Sandbox Code Playgroud)