Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 837
David Thielen Avatar asked Apr 05 '14 01:04

David Thielen


People also ask

How do I cast objects in TypeScript?

If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.


4 Answers

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:

  1. Copying AJAX JSON object into existing Object
  2. Parse JSON String into a Particular Object Prototype in JavaScript

In essence, you'd just :

var d = new MyRichObject();
d.copyInto(jsonResult);
like image 148
WiredPrairie Avatar answered Oct 17 '22 22:10

WiredPrairie


I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.

It works like this :

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

It supports nested children but you have to decorate your class's member.

like image 160
Pak Avatar answered Oct 17 '22 21:10

Pak


In TypeScript you can do a type assertion using an interface and generics like so:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

Where ILocationMap describes the shape of your data. The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface.

However, this does NOT add class instance methods.

like image 71
user756310 Avatar answered Oct 17 '22 22:10

user756310


If you are using ES6, try this:

class Client{
  name: string

  displayName(){
    console.log(this.name)
  }
}

service.getClientFromAPI().then(clientData => {
  
  // Here the client data from API only have the "name" field
  // If we want to use the Client class methods on this data object we need to:
  let clientWithType = Object.assign(new Client(), clientData)

  clientWithType.displayName()
})

But this method will not work on nested objects, sadly.

like image 55
小广东 Avatar answered Oct 17 '22 22:10

小广东