Local storage is not the main concern here. You can store the class as data in JSON format and then restore it to a new instance of the class.
An easy way to do this is by adding a constructor that takes the JSON object and applies it to the class instance:
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;
}
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));
If your goal is simply to hold some data in an object, using an interface might be a more suitable approach. In Typescript, declaring a class with properties for a basic data structure may be unnecessary. Instead, declare an interface and assign object literals to variables of that type, which will work seamlessly 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);