1

consider this simple typescript class

class foo {
    public Name: string;
    constructor(name: string) {
        this.Name = name;
    }

    public bar(): string {
        return this.Name;
    }
}

var test = new foo("foo");
var deserialized = JSON.parse(JSON.stringify(test));
deserialized.bar();//not defined. expected

behavior is totally expected, but what should I do to get the method back?
I looked around and found two candidates: Object.create and Object.setPrototypeOf

I can either do

var test1 = Object.setPrototypeOf(deserialized, foo.prototype);

or

var test2 = Object.create(foo.prototype)
test2 = Object.assign(test2, deserialized);

Both of them seem to work. Is it the right way to do this? is there any danger for playing with the prototype like this? or is there a better way to achieve this?

Steve
  • 11,696
  • 7
  • 43
  • 81
  • If you intend to send an object with it's methods to a remote computer, you are essentially shipping script over, which can be done but is considered a security hazard. (look up the perils of using eval()). Better to have the receiving end have it's own code. – Jim B. Jan 02 '18 at 21:15
  • Possible duplicate of [How do I cast a JSON object to a typescript class](https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class) – user247702 Jan 02 '18 at 21:17
  • @JimBaldwin its the other way around. Server sends back the data in json form and I want to be able to use the methods defined in js – Steve Jan 02 '18 at 21:26

1 Answers1

0

The best way will be use Object.setPrototypeOf + type cast as foo, in result we will get:

var test1 = Object.setPrototypeOf(deserialized, foo.prototype) as foo;

The danger here will be that we cannot guarantee that serialized object is an instance of foo.

I would suggest just check for the properties for safety.

Sergii Rudenko
  • 2,603
  • 1
  • 22
  • 24