How do I initialize a TypeScript object with a JSON object

前端 未结 16 952
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 08:30

I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to this question).

Wha

16条回答
  •  猫巷女王i
    2020-11-22 09:13

    you can use Object.assign I don't know when this was added, I'm currently using Typescript 2.0.2, and this appears to be an ES6 feature.

    client.fetch( '' ).then( response => {
            return response.json();
        } ).then( json => {
            let hal : HalJson = Object.assign( new HalJson(), json );
            log.debug( "json", hal );
    

    here's HalJson

    export class HalJson {
        _links: HalLinks;
    }
    
    export class HalLinks implements Links {
    }
    
    export interface Links {
        readonly [text: string]: Link;
    }
    
    export interface Link {
        readonly href: URL;
    }
    

    here's what chrome says it is

    HalJson {_links: Object}
    _links
    :
    Object
    public
    :
    Object
    href
    :
    "http://localhost:9000/v0/public
    

    so you can see it doesn't do the assign recursively

提交回复
热议问题