How do I cast a JSON Object to a TypeScript class?
json, typescript
Solution
You can't simple cast a plain-old-JavaScript result from an Ajax request into a prototypical JavaScript/TypeScript class instance. There are a number of techniques for doing it, and generally involve copying data. Unless you create an instance of the class, it won't have any methods or properties. It will remain a simple JavaScript object.
While if you only were dealing with data, you could just do a cast to an interface (as it's purely a compile time structure), this would require that you use a TypeScript class which uses the data instance and performs operations with that data.
Some examples of copying the data:
- Copying AJAX JSON object into existing Object
- Parse JSON String into a Particular Object Prototype in JavaScript
In essence, you'd just :
var d = new MyRichObject();
d.copyInto(jsonResult);
Problem
I read a JSON object from a remote REST server. This JSON object has all the properties of a typescript class (by design). How do I cast that received JSON object to a type var? I don't want to populate a typescript var (ie have a constructor that takes this JSON object). It's large and copying everything across sub-object by sub-object & property by property would take a lot of time. Update: You can however cast it to a typescript interface!
Related problems
- Can I create a TypeScript type and use that when AJAX returns JSON data?
- How do I initialize a TypeScript Object with a JSON-Object?
- Parse JSON String into a Particular Object Prototype in JavaScript
- Copying AJAX JSON object into existing Object
- JSON to TypeScript class instance?
- TypeScript - pass to constructor entire object