Xyrin Technologies
Xyrin Technologies

Reputation: 239

Not a function error on TypeScript object after Casting

I made an http call using Angular5 http client. In map function I have done the casting of the response to a PersonModel.

PersonModel has a function getFullName() which returns first_name + last_name

After doing the casting when I try to access this method on casted person object this shows an error of getFullName is not a function.

export class PersonModel {
constructor(
                public first_name: string = null,
                public middle_name: string = null,
                public last_name: string = null) {

    }

getFullName() {
        return this.first_name + this.last_name;
    }

}

This is the service

get(id: number): Observable<PersonModel> {
            return this.http.get("customer/" + id)
                .map((response: any) => {
                    return <PersonModel>response;
                });
        }


customerService.get(1).subscribe(result => {
    console.log(result.getFullName());
})

Error core.js:1350 ERROR TypeError: person.getFullName is not a function

Log for object:

{first_name: "kjlkj", last_name: "jnkjh"}

However when I create an object like this:

const person = new PersonModel();
person.first_name = "lkj";
person.last_name= "lkj";

then this logs as this:

PersonModel {first_name: "kjlkj", last_name: "jnkjh"}

Upvotes: 7

Views: 2500

Answers (2)

vinicius gati
vinicius gati

Reputation: 419

Well , wellcome to JS/TS world.

When you cast basically it is just to avoid type "errors" on your IDE in typescript, and to be sure certain attributes exist on the object but not functions...

class Dog {
    public name: string = "";

    bark(): void {
        console.log("whoof whoof");
    } 
}


let johnny = new Dog();
johnny.name = "johnny";
johnny.bark(); // => Barks ok

let onlyattrs = {
    name: "err"
} as Dog;

// onlyattrs.bark(); // => function does not exists

let realDog = new Dog();
realDog = Object.assign(realDog, onlyattrs);

realDog.bark(); // => barks ok 

Hope this helps.

Upvotes: 8

jrelo
jrelo

Reputation: 238

Try this:

get(id: number): Observable<PersonModel> {
   return this.http.get('customer/' + id).pipe(
      map(p:any=> {return new PersonModel(p.first_name,p.middle_name,p.last_name)});
   );
}

Upvotes: 0

Related Questions