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

标签 javascript 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()))
})

最佳答案

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

相关文章:

javascript - 422 不返回发送消息(Node.js/Redux)

javascript - 从 web worker 发布数据后的引用

typescript - 带有 mousedown、mousemove 和 mouseup 的 Cypress .trigger 命令不起作用

angular - 在 Angular 7 TypeScript 组件的工具栏中使用 Leaflet Draw 插件

javascript - 将部分html文本替换为input val JS

javascript - 在文件结束前添加和删除文本的正则表达式

javascript - Twitter Bootstrap Typeahead gon gem 并将数据从模型传递到 JS - 以 json 格式

typescript - VSCode 和 TypeScript - 在不打开受影响文件的情况下重构/重命名

typescript - jest mock 看不到它在函数中的 if 语句里面被调用了

Angular 4,类型 'XX' 中缺少属性 '{xx, xx}'