ceth
ceth

Reputation: 45295

Cast JSON object to TypeScript class instance

I have a class which have a method:

 export class ItemType {
        id1: string;
        description: string;

        treeItemTypeDescription(): string {
            return this.id1 +  this.description;
        }
 }

I get the data of this class form web service and want to call this method:

itemTypeResource.parents(this.originalPosition).then((parents: app.domain.ItemType[]) => {
      console.log(typeof(parents[0]));
      console.log(parents[0].treeItemTypeDescription());
});

But get the error:

TypeError: parents[0].treeItemTypeDescription is not a function

I think the reason of error the JS-object is not linked with TS-object. But I don't know how to fix it.

Update:

console.log(Object.getOwnPropertyNames(parents[0]));

gives only fields, but not methods:

 ["autoincrementedId", "description", "entityType", "excelId", "excelParentId", "id1", "id2", "id3", "id4", "id5", "parentAutoId"]

Update2:

If I create the object by myself all works fine:

  var s = new app.domain.ItemType();
  s.id1 = "1";
  s.description = "some";
  console.log(s.treeItemTypeDescription());

Upvotes: 2

Views: 1385

Answers (1)

ceth
ceth

Reputation: 45295

Here is a solution I have found:

static fromJSON(json: app.domain.ItemType): app.domain.ItemType {

        var result = new ItemType();

        for (var key in json) {
            if(result.hasOwnProperty(key)) {
                result[key] = json[key]
            }
        }

        return result;
    }

I have created the static method to convert JSON objects to TS objects

Upvotes: 2

Related Questions