0

Does Typescript somehow compatible with local storage? I set item via:

 localStorage.setItem('someString', JSON.stringify(MyTypescriptObject));

which stores object as plain string. For example:

 private _id: string;

 get id(): string {
   return this._id;
 }
 set id(value: string) {
   this._id = value;
 }

and when I get it via:

return <MyTypescriptObject>JSON.parse(localStorage.getItem('someString'));

I get:

{_id: "1"...}

If they are not compatible, I don't see any reason to use Typescript. Even worse, I have to rework all my current code in order to remove it.

IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84

1 Answers1

3

The issue does not really have anything to do with local storage, you can save the class in the data in a JSON format, and then you have to restore the data to a new instance of the class.

You can easily add a constructor that takes the json object and applies it over the instance of the class:

class MyTypescript {
    constructor()
    constructor(id: string, name: string)
    constructor(data: Partial<MyTypescript>)
    constructor() {

        if (arguments.length == 1) {
            let data = arguments[0];
            Object.assign(this, data);
            return
        }
        let id = arguments[0];
        let name = arguments[1];
        this._id = id;
        this._name = name;
    }
    // Alternative to using a constructor, you can use MyTypescript.fromJson(data)
    public fromJson(data?: Partial<MyTypescript>) {
        var result = new MyTypescript();
        Object.assign(result, data);
        return result;
    }
    private _name: string;
    private _id: string;

    get id(): string {
    return this._id;
    }
    set id(value: string) {
    this._id = value;
    }
}

var obj = new MyTypescript();
obj.id = "10";
var data =  JSON.stringify(obj);
var obj2= new MyTypescript(JSON.parse(data));

More generally if all you are looking is for an object to hold some data, an interface might be a better approach. In Typescript it is overkill to declare a class with properties for a simple data class, a common practice is to declare an interface and assign object literals to variables of that type. And that will work more seamless with JSON

interface MyTypescript {
    id: string;
    name: string
}

var obj : MyTypescript = {
    id: "10",
    name: "foo"
};
var data = JSON.stringify(obj);
var obj2: MyTypescript = JSON.parse(data);
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357