Assign ajax result to enable inclusive methods

I am new to Typescript and have a bit of trouble getting my code to work. I have the following interface / class structure

interface IInterface {
  id : number;
  method() : string;
}

class IClass implements IInterface {
  id : number;
  method() : string { return "foo";}
}

Now I want to get some data from the web service through the next call

$.get("/some/url", (data : Array<IInterface>) => {
    for (var i = 0; i < data.length; i++) {
        console.log(data[i].id);
        console.log(data[i].method());
    }
});

Although this compiles fine in Typescript, and all properties are set fine, I get a runtime TypeError data[i].method is not a function

So now my question is: how can I draw / assign (?) Correctly so that the methods are also available in the resulting JavaScript?

UPDATE As requested: Dump the data I get from the web service.

data = [{id : 1}, {id : 2}, ...]  

, : / ( ), ( , , ).

+1
2

, , , method.

, , IClass , data:

$.get("/some/url", (data: Array<IInterface>) => {
    return data.map((d) => return new IClass(d.id));
});
+1

JSON . , : JSON TypeScript ?

, :

export class Helper
{
    public static DESCRIPTOR_SIGN = '$';

    private static m_entityModules = [];

    private static ReviveDateTime(key: any, value: any): any 
    {
        if (typeof value === 'string')
        {
            let a = /\/Date\((\d*)\)\//.exec(value);
            if (a)
            {
                return new Date(+a[1]);
            }
        }

        return value;
    }

    private static RessurectValue(json: any, environments: any[]): any
    {
        if(json == null)
        {
            return null;
        }
        else if(Helper.IsString(json))
        {
            return json;
        }
        else if(json instanceof Date)
        {
            return json;
        }
        else if(typeof json === 'object') 
        {
            return Helper.RessurectInternal(json, environments);
        } 
        else 
        {
            return json;
        }
    }

    private static RessurectInternal(json: any, environments: any[]): any 
    {
        var instance;

        if(!json[Helper.DESCRIPTOR_SIGN])
        {
            instance = {};
        }
        else
        {
            instance = Helper.CreateObject(json[Helper.DESCRIPTOR_SIGN]);

            if(Helper.IsUndefined(instance))
            {
                throw new Error('Unknown type to deserialize:' + json[Helper.DESCRIPTOR_SIGN]);
            }              
        }

        for(var prop in json) 
        {
            if(!json.hasOwnProperty(prop) || prop === Helper.DESCRIPTOR_SIGN) 
            {
                continue;
            }

            let val = json[prop];
            instance[prop] = Helper.Ressurect(val, environments);
        }

        return instance;
    }

    private static CreateObject(className: string, environments?: any[]): any
    {
        let instance: any;
        for(let e of environments)
        {
            var construct = e[className];

            if(!Helper.IsUndefined(construct))
            {
                instance = new construct(); 
                break;
            }
        }

        return instance;
    }

    private static IsNumber(val: any): boolean
    {
        return typeof val == 'number' || val instanceof Number;
    }

    private static IsUndefined(val: any): boolean
    {
        return typeof(val) === 'undefined';
    }

    private static IsString(val: any): boolean
    {
        return typeof val == 'string' || val instanceof String;
    }

    /**
     * Deserialize json object object into TypeScript one.
     * @param json json object that must have its class name in '$' field
     * @param environments list of modules containing all types that can be encountered during deserialization
     * @return deserialized typescript object of specified type  
     */
    public static Ressurect(val: any, environments: any[]): any 
    {
        if(val instanceof Array)
        {
            if(val.length == 0)
            {
                return val;
            }
            else 
            {
                let firstElement = val[0];
                if(typeof firstElement !== 'object')
                {
                    return val;
                }
                else
                {
                    let arr = [];
                    for (var i = 0; i < val.length; i++) 
                    {
                        var element = val[i];
                        arr.push(Helper.RessurectValue(element, environments));
                    }

                    return arr;
                }   
            }
        }
        else
        {
            return Helper.RessurectValue(val, environments);
        }
    }
}

. , :

  • , , .
  • JSON '$' .

. , yu "". , JSON, :

import * as types from './Types'

//Some code to get jsonObj that has jsonObj.$ set to "RealObject" - a type from "Types" module

let realObj = <types.RealObject>Helper.Resurrect(jsonObj, [types]);

, .

+1

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


All Articles