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);