【问题标题】:Typescript interface call methodTypescript接口调用方法
【发布时间】:2018-05-06 09:58:01
【问题描述】:

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

元素类:

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;
}

我使用 Angular 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
        }
    }

我的错误在哪里?我收到错误“ERROR TypeError: entity.GetName is not a function”

【问题讨论】:

  • 嗨,从你的错误来看,deleteClick(ele: Element) 中的ele 不是Element,它在哪里实例化?

标签: typescript interface


【解决方案1】:

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

let name = entity['GetName()']

【讨论】:

  • 嗨(欢迎光临),我认为这更多的是类型错误而不是语法错误
猜你喜欢
  • 2020-04-06
  • 2023-04-03
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多