Parsing JSON from Typescript restores data members but not type: cannot call methods on result

json, typescript

Solution

try this:

// Create a person
var p: Person  = new Person("One", 1);

// JSON roundtrip
var p_fromjson = JSON.parse(JSON.stringify(p))

// Hydrate it
var p2: Person = Object.create(Person.prototype);
Object.assign(p2, p_fromjson);

document.writeln(p2.Age()); // OK

Problem

When I parse the JSON-stringified result of an object p1 back into another object p2, the second object gets the data associated with the first object, but I cannot call any nethods on it. Using http://www.typescriptlang.org/Playground/ I tried the following: ``` class Person { constructor(public name: string, public age: number) { } Age() { return this.age; } } // Create a person var p: Person = new Person("One", 1); // Create a second person from the JSON representation // of the first (NOTE: assert it is of type Person!) var p2: Person = <Person>JSON.parse(JSON.stringify(p)); document.writeln("Start"); document.writeln(p.name); // OK: One document.writeln(p.Age()); // OK: 1 document.writeln(p2.name); // OK: One document.writeln(p2.age; // OK: 1 document.writeln(p2.Age()); // ERROR: no method Age() on Object document.writeln("End"); ``` How do I parse the JSON data and get a proper Person object?

Original source