Nibras
Nibras

Reputation: 369

Cannot access object property values in Typescript

I'm getting some JSON object stored from HTML5 local storage and assign it to an object.

this.currentWebUser = Object.assign({}, JSON.parse(localStorage.getItem("currentUser")));

currentWebUser is an object of class my class WebUser

export class WebUser {
  private _id: number;
  private _connectionID: number;

  public set id(value: number) {
    this._id = value;
  }

  public get id(): number {
    return this._id;
  }

  public set connectionID(value: number) {
    this._connectionID = value;
  }

  public get connectionID(): number {
    return this._connectionID;
  }
}   

When I try to get the value of id by using this.currentWebUser.id (In typescript this refer getter method of id) I'm getting undefined value, not the actual value.

enter image description here

But in chrome console, I can see the actual value is there.

enter image description here

Need help, Thanks in advance !!!

Upvotes: 1

Views: 1610

Answers (1)

Lesiak
Lesiak

Reputation: 26084

The problem is that the value returned by

Object.assign({}, JSON.parse(localStorage.getItem("currentUser")));

is not an instance of your WebUser class. It is an Object with the fields that were present in the Json (which is clearly visible in your debugger screenshot).

You can check currentWebUser.__proto__.constructor to see that it points to Object(), not WebUser()

You are able to assign the result of Object.assign to currentWebUser variable because return type of Object.assign is any.

You need to make sure that you deserialise to the instance of your class. There are a few ways to do it, see the following links

let webUser = Object.assign({}, JSON.parse('{"_connectionID": 1, "_id":2}'));
let webUser2 = Object.assign(
  new WebUser(),
  JSON.parse('{"_connectionID": 1, "_id":2}')
);
console.log(webUser);
console.log(webUser2);

Output:

{_connectionID: 1, _id: 2}          // Your code
WebUser {_connectionID: 1, _id: 2}  // What you expect

Upvotes: 2

Related Questions