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

sel*_*lf. 11 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()))
})
Run Code Online (Sandbox Code Playgroud)

Nit*_*mer 18

您可以使用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);
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这是您需要更多类的东西,那么您可以拥有一个具有此方法的基类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,这不会将任何对象属性转换为 JS 对象,它们将保留为任何类型的实例。请参阅以下示例:https://www.typescriptlang.org/play/#code/MYGwhgzhAECC0G8C+AoFpIwEKJdaADgK4BGIAlsNAG5ggBcc0AvNAHYCmA7nABQCUAbhSoUIDgBdoADxbtu0LAOEo6HAE4Tes8mwgSwbYBwD2AM0VDoAemvQAkuqIdV4zdoB0tENF37 DxuZwVrYOTi5iktAAnnIA8iQAVhzAEh6Y5ADmbLzIADQyQmhq7rF+BkamFlghdgBidBAuJVrRXnS+ehWBFrC1Yc4oQA (4认同)

Ala*_*ois 6

像这样的事情很简单,而且很有效:

let plainObj;
try {
    plainObj = JSON.parse(JSON.stringify(obj));
} catch(e) {
    console.error(e)
}
Run Code Online (Sandbox Code Playgroud)