如何将 TypeScript 对象转换为普通对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/37300338/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a TypeScript object to a plain object?
提问by self.
I'm using a JS library, specifically select2that acts a tad differently than I'd like if the objects I'm passing it aren't plain objects. This is all checked by using jQuery's isPlainObjectfunction.
我正在使用一个 JS 库,特别select2是如果我传递的对象不是普通对象,它的行为与我想要的有点不同。这都是通过使用 jQuery 的isPlainObject函数来检查的。
Does TypeScript have a cast I'm unaware of that would achieve this without resorting to writing my own?
TypeScript 是否有一个我不知道的演员阵容,可以在不诉诸自己编写的情况下实现这一目标?
class Opt {
    constructor(public id, public text) {
    }
    toPlainObj(): Object {
        return {
            id: this.id,
            text: this.text
        }
    }
}
let opts = [
    new Opt(0, 'foo'),
    new Opt(1, 'bar')
];
console.clear()
console.log('both should be false')
$.map(opts, opt => {
    console.log($.isPlainObject(opt))
})
console.log('both should be true')
$.map(opts, opt => {
    console.log($.isPlainObject(opt.toPlainObj()))
})
回答by Nitzan Tomer
You can use Object.assign():
您可以使用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);
p1is the class instance, and p2is just { x: 4, y: 5 }.
p1是类实例,并且p2只是{ x: 4, y: 5 }.
And with the toPlainObjmethod:
并使用toPlainObj方法:
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;
    }
}
回答by Alain Beauvois
Something like this is simple and it works :
像这样的事情很简单,而且很有效:
let plainObj;
try {
    plainObj = JSON.parse(JSON.stringify(obj));
} catch(e) {
    console.error(e)
}

