Method in typescript class gives error "not function"

I am working on an Angular2 web application. I created a simple class in typescript:

export class User {
    firstName: string;
    lastName: string;

    nominative() : string {
        return this.lastName + " " + this.firstName;
    }
}

When I call nominativeon the type of object User, I get this error: Error in :0:0 caused by: user.nominative is not a function.

I call the function in the class AppComponent:

export class AppComponent implements OnInit {
    name: string = "";

    ngOnInit() : void {
        let user = JSON.parse(sessionStorage.getItem("User")) as User;
        if (user) {
            this.name = user.nominative();
        }
    }
}

I already tried using a lambda expression like this:

nominative = () : string => { ... }

But nothing changes. The only problem is in this class, so what am I doing wrong?

+4
source share
1 answer

as Usertells the compiler that it is safe to assume that the value is of type User, but does not affect the execution time, and it will not have any methods because the methods are not passed with JSON.

You will need

let user = new User(JSON.parse(sessionStorage.getItem("User")));

User. , JSON ,

class User {
  ...
  constructor(json:any) {
    this.firstName = json.firstName;
    this.lastName = json.lastName;
  }
+9

Source: https://habr.com/ru/post/1672709/


All Articles