Andrea
Andrea

Reputation: 795

Function defined, but MyFunction is not a function

Person is object with a firstName and a lastName properties. I have a service which returns some Person. In order to model Person in Typescript, I have created the following Person.ts class:

export class Person {

    firstName?: string;
    lastName?: string;

    get fullName(): string() {
        return `${firstName} ${lastName}`;
    }

}

I'm able to retrieve an array of Person with the following code:

this.persons: Array<Person> = this.httpClient.get<Array<Person>>('http://url.of.my.service');

For every Person in this.persons, I'm able to get it's first name and last name, but I get the following error if I try to get it's full name: person.fullName is not a function. What does it mean?

Upvotes: 0

Views: 53

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

There are two problems with your code.

The obvious one is that fullName is not a function, it's a property, as such it should be accessed person.fullName not person.fullName()

The second problem is that this.httpClient.get<Array<Person>>('http://url.of.my.service'); will not return instances of Person it will return objects that may have the fields of Person but will not be instances of Person and thus the property fullName will not exist as you have defined it on the objects returned by that call. (Also guessing it does not directly return an array, looks like an Angular service returning an Observable)

You will need to transform the object to an instance of the class, using Object.assign for example.

Upvotes: 3

Quentin
Quentin

Reputation: 943207

get fullName()

It is a getter, not a regular function.

When you access the fullName property it will implicitly call the function and give you the return value (which is a string).

Trying to call fullName() will try to treat that string as a function, which it isn't.

If you had defined it without the get, then you could call fullName().

Upvotes: 1

Related Questions