2

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.

2
  • perhaps you are looking for something like stackoverflow.com/questions/36517173/… Commented Jul 13, 2018 at 13:05
  • for Titian answer below, Object assign does not deep copy items, is there a better way to bring back methods with something like lodash ngdeep? medium.com/better-programming/… Commented Mar 16, 2020 at 3:57

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

hi, Object assign does not deep copy items, is there a better way to bring back methods with something like lodash ngdeep? medium.com/better-programming/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.