Thursday, 8 June 2017

Casting JSON Object to TypeScript Class

I have implemented some HTTP service for my Angular App using the explanation at [1]. Now in resource [2] it is mentioned that it is important to provide the JSON Object received from the HTTP Service in the constructor of the data model.

I thought I had found a shortcut. I thought that as long as the JSON object received resembled the structure of the TypeScript class, that I could just cast it to the TypeScript class.

This worked fine, until it didn't, and then I got this huge error in my face.

The problem

The problem started appearing when I defined a method in my TypeScript class. Naturally, this method is not available in the JSON Object, and no manner of Casting is going to make it magically appear there.

You get something like:
ERROR TypeError: item.getItemPriceAsInteger is not a function
    at ItemService.webpackJsonp.71.ItemService.updateItem (
    at ItemSettingsComponent.webpackJsonp.183.ItemSettingsComponent.update (
    at ItemSettingsComponent.webpackJsonp.183.ItemSettingsComponent.saveItem (
    at Object.eval [as handleEvent] (ng:///AppModule/ItemSettingsComponent.ngfactory.js:1663:24)
    at handleEvent (
    at callWithDebugContext (
    at Object.debugHandleEvent [as handleEvent] (
    at dispatchEvent (
    at SafeSubscriber.schedulerFn [as _next] (


There are several solutions available as described in [3, 4, 5].

Chosen solution

I like the one provided in [6]. It uses TypeScript Decorators7. It can be installed as an npm package, according to [8].

To anyone using Java, the solution provided has an uncanny resemblance to JPA annotated Entities or JAXB annotated classes.

I am going to go ahead and try this one out, and see how it works.

I'll provide an update, once I get some results.


[1] Angular Docs - HTTP Client
[2] Writing a Search Result
ng-book 2 - The Complete Book on Angular Nate Murray, Felipe Coury, Ari Lerner, Carlos Taborda
[3] StackOverflow - How do I cast a JSON object to a typescript class
[4] StackOverflow - Angular2 cast a json result to an interface
[5] Angular2 HTTP GET - Cast response into full object
[6] Mark Galae - TypeScript Json Mapper
[7] TypeScript - Decorators
Ninja Tips 2 - Make your JSON typed with TypeScript
[8] npm - json-typescript-mapper


  1. This comment has been removed by the author.

  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from TypeScript Online Training . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  3. We've found that casting doesn't work on nested objects including dates. Only the top level is actually cast. If your subproperty is defined as an object, its still being returned as a string.