[Fixed] get methods return undefined in Typescript


I don’t undertand what’s my code error when defining the get and set methods for a private field.

export class User{
  private userName = "defaultName";

  constructor(private token:string){}

  public get UserName():string{
    return this.userName;

  public set UserName(value:string){
    this.userName = value;

  public get Token():string{
    return this.token;

  public set Token(value:string){
    this.token= value;

When I try the following code I get undefined values.

    const user:User = JSON.parse(localStorage.getItem("user"));


The problem is not about the get methods. I tried to read fields of a custom object (User) using data retrieved from localStorage:

 const user:User = JSON.parse(localStorage.getItem("user"));

With that code I’m able to read public fields but not the private ones using the get methods, because when you JSON.parse data (in my case retrieved from localStorage) you obtain a plain javascript object, even if you try to "typify" the variable this way: user:User.

I tried to access the field using the get method user.UserName that actually doens’t exist on the plain javascript object I created with JSON.parse; inside this plain javascript object there is only the field user.username. What I tried to do is not possible (I suppose).


That code should work. Playground

Why didn’t your example work out?

When you parse item from local storage user variable becomes something like this:
{ userName: "John", token: 30 }

But you accessing user.UserName which does not exists so you have to mimic object from localStorage like so user.userName.

Ways to fix it:

  1. Create new instance of the User class
const userFromLocalStorage = JSON.parse(JSON.stringify({ userName: "John", token: 30 }));
const user = new User(userFromLocalStorage.userName, userFromLocalStorage.token)
  1. Create getters/setters that mimic shape of object like in example below

Things to consider.

  • In typescript we don’t write capitalized setters or getters
  • Use this approach for naming private variables private _userName = "defaultName"; with underscore
  • Doing this constructor(public token:string){} you don’t have to create setters or getters.
export class User{
  private _userName = "defaultName";

  constructor(username, public token:string){
    this.userName = username;

  public get userName():string{
    return this._userName;

  public set userName(value:string){
    this._userName = value;
const user: User = JSON.parse(JSON.stringify({ "userName":"John", "token":30 }))

Typescript documentation

Leave a Reply

(*) Required, Your email will not be published