80

I work on 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 nominative on object of type User I receive this error: Error in :0:0 caused by: user.nominative is not a function.

I call the function in my AppComponent class:

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 to use lambda expression in this way:

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

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

0

2 Answers 2

66

as User only tells the compiler that it's safe to assume that the value is of type User, but doesn't have any effect on runtime and it won't have any methods because methods are not passed with JSON.

You would need

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

to get an actual User instance. You would need to create a constructor that assigns the values from JSON to fields like

class User {
  ...
  constructor(json:any) {
    this.firstName = json.firstName;
    this.lastName = json.lastName;
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Another option is to do Object.assign(new User(), JSON.parse(sessionStorage.getItem("User")))
I have the exact same error, but I do not read from Json. My constructor is empty.class A(){ doThing(): void {...}} export default new A When I call A.doThings() I got doThings is not a function..
I'm not really into TypeScript :D I'd try removing new between default ... A or add () at the end ... export default new A().
Typescript is a **** when things like this exist... Why do we use this language again?
@Michael It's all about managing expectations ;-) This is a compile-time feature and it doesn't have an effect at runtime because that would be way too much of a performance burden. They did great work IMHO considering the restrictions of the platform (and I'm all but an MS fan)
0

This video explains it pretty well. Turns out you need to check to see if the class's method exists before calling it. I'm still not exactly sure why this happened on one of my pages while I had instances of classes with methods all over my program, but it worked. https://www.youtube.com/watch?v=SdAt1qbWB-o/

if(this.searchResult.clearResults){
      this.searchResult.clearResults()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.