I have a TypeScript model object called user
export class User {
constructor(
private _name: string,
private _email: string
) {}
public get name():string {
return this._name;
}
public set name(value:string) {
this._name = value;
}
get email():string {
return this._email;
}
set email(value:string) {
this._email = value;
}
}
The object is stored in local storage using the following code:
let user = new User('myName', 'myEmail');
localStorage.setItem('user', JSON.stringify(user));
After checking the local storage, I found the following string representation of the object:
{"_name":"myName","_email":"myEmail"}
How can I retrieve the user object correctly?
let user: User = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // This logs undefined. It should log 'myName'
console.log(user._name); // Surprisingly, this logs 'myName'. According to TypeScript documentation, this should not work!
I believe the issue has to do with the underscores used when storing the object. How can I properly access the object values?