Typescript interface call method

Viewed 2630

I want to use a class "element" with has an interface "entity". I would like to use the interface like c# interfaces. I have an angular component with an input. The input type is entity (the interface) because the angular component has two input classes. I thought I can use an interface like c# where I define a method that I implement in the other classes (example: "element") and call this method over the element instace that is casted to an interface. I hope you can understand that what I want to do.

Element class:

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

Entity class:

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

I use a dialog from angular material 2. I give the dialog the right input type "element" (base class).

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

In the dialog:

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

Where is my mistake? I get the error "ERROR TypeError: entity.GetName is not a function"

1 Answers

Please try to call the function as shown below

let name = entity['GetName()']
Related