How do I initialize a TypeScript object with a JSON object

前端 未结 16 951
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  感动是毒
    2020-11-22 09:15

    Another option using factories

    export class A {
    
        id: number;
    
        date: Date;
    
        bId: number;
        readonly b: B;
    }
    
    export class B {
    
        id: number;
    }
    
    export class AFactory {
    
        constructor(
            private readonly createB: BFactory
        ) { }
    
        create(data: any): A {
    
            const createB = this.createB.create;
    
            return Object.assign(new A(),
                data,
                {
                    get b(): B {
    
                        return createB({ id: data.bId });
                    },
                    date: new Date(data.date)
                });
        }
    }
    
    export class BFactory {
    
        create(data: any): B {
    
            return Object.assign(new B(), data);
        }
    }
    

    https://github.com/MrAntix/ts-deserialize

    use like this

    import { A, B, AFactory, BFactory } from "./deserialize";
    
    // create a factory, simplified by DI
    const aFactory = new AFactory(new BFactory());
    
    // get an anon js object like you'd get from the http call
    const data = { bId: 1, date: '2017-1-1' };
    
    // create a real model from the anon js object
    const a = aFactory.create(data);
    
    // confirm instances e.g. dates are Dates 
    console.log('a.date is instanceof Date', a.date instanceof Date);
    console.log('a.b is instanceof B', a.b instanceof B);
    
    1. keeps your classes simple
    2. injection available to the factories for flexibility

提交回复
热议问题