小编pio*_*eqd的帖子

打字稿转换总是返回“对象”

假设我有两个接口,它们有两个相同的成员 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)

casting type-conversion type-assertion typescript angular

3
推荐指数
1
解决办法
1069
查看次数