Aisatora
Aisatora

Reputation: 352

Missing methods in TypeScript class

I have a TypeScript model which contains properties and functions like:

class Person {
name: string
sayHello(){ console.log(name); }
}

When creating its instance I can make use of this sayHello() method as expected.

The problem comes when I store and get the object from the local storage or an external web service. While the properties are still present the methods have disappeared. (obviously because it’s just text).

Is there any way to restore the completeness of the object to be able to use its functions?

Or otherwise, is there any other technique? For instance, helper class that can work with type.

Upvotes: 2

Views: 4276

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250376

When you save to a local storage, you will save a JSON representation of the class data; when you get the object back from the local storage, it will be just an object, not an instance of the original class.

You can look for an external library that will help you with this, but the simple solution is to create a new instance of the class and assign the field values to the class using Object.assign:

class Person {
    public constructor(public name?: string){}
    sayHello() { console.log(name); }
}
let p = new Person("Test");
let data = JSON.stringify(p);
let p2 = new Person()
Object.assign(p2, JSON.parse(data));

Upvotes: 3

Related Questions