Typescript class method undefined

In Typescript I have a class Contact

that implements an interface IContact

. I want to add a property or function to a class Contact

that returns a combination of two other fields (first and last name). The interface definition IContact

looks like this:

export interface IContact {
    firstname: string;
    lastname: string;
}

      

The class Contact

looks like this:

export class Contact implements IContact {
    constructor(
        public firstname: string,
        public lastname: string
    ) { }

    public fullname(): string {
        return this.firstname + " " + this.lastname;
    }
}

      

In my view, I want to output the result Contact.fullname()

, but I am getting an error that is fullname

not a function. I have access to all other properties of this class.

==== UPDATE ===

I'll add some extra code to make things clear. When I infer the property fullname

, in my opinion, I tried Contact.fullname()

, but also contact.fullname

, which results in nothing. In my component, trying to figure out what's going on, I tried to output fullname

to the console like this console.log("FULLNAME " +contact.fullname());

, but that gives me the following message in the console:EXCEPTION _this.contact.fullname is not a function

===== UPDATED FROM ANSWERS ========

As Sakuto correctly said, the contact list is created by some json received from the server. By creating a whole new instance, calling it with the constructor, I was able to infer the property fullname

. Thank you Sakuto!

+3


source to share


1 answer


You are probably trying to call this method on an object dynamically cast from JSON

. Dynamically casted object

has no method defined in the class, they just respect contract

and possess the property.

The only way to get your current code to work is to create a new instance Contact

instead of just throwing it on <Contact> yourObject

;



The solution is to do something like this:

let contactsList: Contact[] = [];
yourServiceReturn.ForEach(c => contactsList[] = new Contact(c.name, c.surname));
// You can now call getFullName on the object stored on contactsList 

      

+7


source







All Articles