[SOLVED] Typescript objects serialization?

Issue

Are there any means for JSON serialization/deserialization of Typescript objects so that they don’t loose type information? Simple JSON.parse(JSON.stringify) has too many caveats.

Or I should use adhoc solutions?

Solution

Use Interfaces to get strong types:

// Creating 
var foo:any = {};
foo.x = 3;
foo.y='123';

var jsonString = JSON.stringify(foo);
alert(jsonString);


// Reading
interface Bar{
    x:number;
    y?:string; 
}

var baz:Bar = JSON.parse(jsonString);
alert(baz.y);

And use type assertion “<>” if you need to.

Answered By – basarat

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *