Javascript 如何将TypeScript对象转换为普通对象?
我使用的是一个JS库,特别是Javascript 如何将TypeScript对象转换为普通对象?,javascript,typescript,Javascript,Typescript,我使用的是一个JS库,特别是select2,如果我传递的对象不是普通对象,它的行为与我希望的稍有不同。所有这些都是使用jQuery的isPlainObject函数检查的 TypeScript是否有一个我不知道的演员阵容,如果不用我自己写的话就能达到这个目的 class Opt { constructor(public id, public text) { } toPlainObj(): Object { return { id:
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()))
})
您可以使用:
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;
}
}
类基类{
toPlainObj():T{
返回Object.assign({},this);
}
}
类点扩展了基类{
私人x:数字;
私人y:数字;
构造函数(x:编号,y:编号){
超级();
这个.x=x;
这个。y=y;
}
getX():编号{
归还这个.x;
}
getY():数字{
把这个还给我;
}
}
类似的东西很简单,而且很有效:
let plainObj;
try {
plainObj = JSON.parse(JSON.stringify(obj));
} catch(e) {
console.error(e)
}
我知道这是一篇老文章,但是在上面Nitzan的回答中,typescript语法检查器似乎可以只执行以下操作:
const plainObj:any=ClassObj;
ClassObj.newProperty=“测试”;
因此,似乎没有真正需要使用Object.assign,除非我不知道有什么不同。请发布您的代码here@messerbill我不相信代码片段支持TypeScript。至少,我无法让它工作。只需在此处键入它-您不需要使用代码段功能太棒了!我正要发火,但这个答案救了我一命:)我正在寻找完全相反的答案。有普通js对象,要将其转换为特定类型。@模制如下内容:?值得一提的是,这不会将任何对象属性转换为js对象,它们将保留为任何类型的实例。请参见以下示例:@Qyaffer您知道有什么方法可以将对象实例属性转换为普通对象吗?
let plainObj;
try {
plainObj = JSON.parse(JSON.stringify(obj));
} catch(e) {
console.error(e)
}