如何将 TypeScript 对象转换为普通对象?

新手上路,请多包涵

我正在使用一个 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 许可协议

阅读 429
2 个回答

您可以使用 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;
    }
}

原文由 Nitzan Tomer 发布,翻译遵循 CC BY-SA 3.0 许可协议

这样的事情很简单并且有效:

 let plainObj;
try {
    plainObj = JSON.parse(JSON.stringify(obj));
} catch(e) {
    console.error(e)
}

原文由 Alain Beauvois 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题