Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method in typescript class give error "is not a function"

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?

like image 677
erikscandola Avatar asked Mar 20 '17 09:03

erikscandola


People also ask

Is not a function error in TypeScript?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.

Is not a function console error?

In short, the "is not a function" error means that the value you're trying to invoke is not a function. The most common reasons this error occurs are: defining a variable with the same name that shadows the original object. calling a method on a value of a different type, e.g. calling the Array.

What is not a function?

A function is a relation in which each input has only one output. In the relation , y is a function of x, because for each input x (1, 2, 3, or 0), there is only one output y. x is not a function of y, because the input y = 3 has multiple outputs: x = 1 and x = 2.

Is not a function test?

The "test is not a function" error occurs when the test() method is called on a value that is not a regular expression, e.g. a string. To solve the error, make sure to only call the test method on regular expressions, e.g. /[a-b]/. test('abc') . Here is an example of how the error occurs.


1 Answers

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;   } 
like image 81
Günter Zöchbauer Avatar answered Oct 24 '22 15:10

Günter Zöchbauer