Typescript接口(interface)调用方法

标签 typescript interface

我想使用具有接口(interface)“实体”的类“元素”。我想使用像 c# 接口(interface)这样的接口(interface)。我有一个带输入的角度分量。输入类型是实体(接口(interface)),因为角度组件有两个输入类。我想我可以使用像 c# 这样的接口(interface),我在其中定义了一个在其他类中实现的方法(例如:“元素”),并在转换为接口(interface)的元素实例上调用此方法。我希望你能明白我想做什么。

元素类:

import { Entity } from "./entity";

export class Element implements Entity {
    public Id: string;
    public Name: string;
    public ShortDesc: string;
    public Description: string;
    public Picture: any;

    public GetId(): string {
        return 
    }

    public GetName(): string {
        return this.Name;
    }

    public GetType(): string {
        return typeof(this);
    }
}

实体类:

export interface Entity {
    GetId(): string;
    GetName(): string;
    GetType(): string;
}

我使用了角度 Material 2 中的对话框。我为对话框提供了正确的输入类型“元素”(基类)。

    deleteClick(ele: Element) {    
        let dialogRef = this.dialog.open(DeleteDialog, {
        height: '400px',
        width: '400px',
        data: {
            entity: ele
        }
    });

在对话框中:

export class DeleteDialog implements OnInit {

    ngOnInit() {
    }

    dialogResult: string = 'cancel';

    constructor(
        public dialogRef: MatDialogRef<DeleteDialog>,
        @Inject(MAT_DIALOG_DATA) public data: {
            type: string,
            entity: Entity
        },
        private globalServ: GlobalService) {
            let entity = this.data.entity;
            let name = entity.GetName();
            //Here I get the Exception ERROR TypeError: entity.GetName is not a function
        }
    }

我的错误在哪里?我收到错误“错误 TypeError:entity.GetName 不是函数”

最佳答案

请尝试调用如下所示的函数

let name = entity['GetName()']

关于Typescript接口(interface)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438485/

相关文章:

node.js - 是否可以测试 Jest 测试?

javascript - 获取错误 promise 在 IE11 中未定义

javascript - Angular ngStyle 解析器错误 : Unexpected token [, 需要标识符或关键字

javascript - tsconfig.json 与 Node.js 模块一起使用的最佳设置是什么?

c# - 如何使多个 SOAP Web 服务调用通用以减少冗余?

oop - 将接口(interface)的定义与其实现分离

c++ - 与模板方法的接口(interface)

c++ - C++中的抽象类与接口(interface)

c# - 自定义集合实现 IEnumerable

typescript - 如何从 "next/app"将自定义类型属性添加到 AppProps 类型?