Insert a JSON object into an instance of the TypeScript class

I have a class that has a method:

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

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

I get data from 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 cause of the JS object error is not related to the TS object. But I do not know how to fix it.

Update:

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

contains only fields, but not methods:

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

Update2:

If I create the object myself, everything works fine:

  var s = new app.domain.ItemType();
  s.id1 = "1";
  s.description = "some";
  console.log(s.treeItemTypeDescription());
+2
source share
1 answer

Here is the solution I 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 created a static method to convert JSON objects to TS objects

+2
source

Source: https://habr.com/ru/post/1659496/


All Articles