Consider a scenario where there are two interfaces with identical members 'id' and 'name':
export interface InterfaceA {
id: number;
name: string;
//some other members
}
export interface InterfaceB {
id: number;
name: string;
//some other members
}
The goal is to gather elements from both types to populate a combobox with their id, name, and type. For this purpose, a class is created as shown below:
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; //always 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)));
})
}
However, the issue arises where the type in the constructor always resolves to "object" and the reason behind this behavior remains unclear. One possible workaround involves using an enum, but the focus is on understanding why the current solution is not functioning as expected without altering InterfaceA or InterfaceB.