How can I convert a TypeScript object to a plain object?

后端 未结 3 1512
故里飘歌
故里飘歌 2021-02-18 21:59

I\'m using a JS library, specifically select2 that acts a tad differently than I\'d like if the objects I\'m passing it aren\'t plain objects. This is all checked b

相关标签:
3条回答
  • 2021-02-18 22:04

    Something like this is simple and it works :

    let plainObj;
    try {
        plainObj = JSON.parse(JSON.stringify(obj));
    } catch(e) {
        console.error(e)
    }
    
    0 讨论(0)
  • 2021-02-18 22:23

    I know this is an old post, however in Nitzan's answer above, the typescript syntax checker seems to be ok with just doing the following:

    const plainObj:any = ClassObj;
    ClassObj.newProperty = "Test";
    

    So it seems like there is no real need to use Object.assign unless there is a difference I am unaware of.

    0 讨论(0)
  • 2021-02-18 22:24

    You can use Object.assign():

    class Point {
        private x: number;
        private y: number;
    
        constructor(x: number, y: number) {
            this.x = x;
            this.y = y;
        }
    
        getX(): number {
            return this.x;
        }
    
        getY(): number {
            return this.y;
        }
    }
    
    let p1 = new Point(4, 5);
    let p2 = Object.assign({}, p1);
    

    p1 is the class instance, and p2 is just { x: 4, y: 5 }.

    And with the toPlainObj method:

    class Point {
        private x: number;
        private y: number;
    
        constructor(x: number, y: number) {
            this.x = x;
            this.y = y;
        }
    
        getX(): number {
            return this.x;
        }
    
        getY(): number {
            return this.y;
        }
    
        toPlainObj(): { x: number, y: number } {
            return Object.assign({}, this);
        }
    }
    

    If this is something you need in more classes then you can have a base class which has this method:

    class BaseClass<T> {
        toPlainObj(): T {
            return Object.assign({}, this);
        }
    }
    
    class Point extends BaseClass<{ x: number, y: number }> {
        private x: number;
        private y: number;
    
        constructor(x: number, y: number) {
            super();
    
            this.x = x;
            this.y = y;
        }
    
        getX(): number {
            return this.x;
        }
    
        getY(): number {
            return this.y;
        }
    }
    
    0 讨论(0)
提交回复
热议问题