我正在使用一个 JS 库,特别是 select2
如果我传递给它的对象不是普通对象,它的行为与我想要的有点不同。这一切都通过使用 jQuery 的 isPlainObject
函数进行检查。
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()))
})
最佳答案
您可以使用 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
是类实例,p2
只是 { x: 4, y: 5 }
。
并使用 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);
}
}
如果这是您在更多类中需要的东西,那么您可以拥有一个具有此方法的基类:
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;
}
}
关于javascript - 如何将 TypeScript 对象转换为普通对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37300338/