HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How do I cast a JSON object to a TypeScript class?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptobjecthowclasscastjson

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 (i.e. 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.

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);

Code Snippets

var d = new MyRichObject();
d.copyInto(jsonResult);

Context

Stack Overflow Q#22875636, score: 228

Revisions (0)

No revisions yet.