How do I initialize a TypeScript object with a JSON object

前端 未结 16 699
被撕碎了的回忆
被撕碎了的回忆 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:03

    the best I found for this purpose is the class-transformer. github.com/typestack/class-transformer

    That's how you use it:

    Some class:

    export class Foo {
    
        name: string;
    
        @Type(() => Bar)
        bar: Bar;
    
        public someFunction = (test: string): boolean => {
            ...
        }
    }
    
    
    import { plainToClass } from 'class-transformer';
    
    export class SomeService {
    
      anyFunction() {
    u = plainToClass(Foo, JSONobj);
     }
    

    If you use the @Type decorator nested properties will be created, too.

提交回复
热议问题