我正在使用一个 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()))
})
原文由 self. 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 Object.assign() :
p1
是类实例,而p2
只是{ x: 4, y: 5 }
。并使用
toPlainObj
方法:如果这是您在更多类中需要的东西,那么您可以拥有一个具有此方法的基类: