Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  166] [ 3]  / answers: 1 / hits: 31252  / 8 Years ago, wed, may 18, 2016, 12:00:00

I'm using a JS library, specifically select2 that acts a tad differently than I'd like if the objects I'm passing it aren't plain objects. This is all checked by using jQuery's isPlainObject function.



Does TypeScript have a cast I'm unaware of that would achieve this without resorting to writing my own?



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()))
})

More From » typescript

 Answers
6

You can use 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 is the class instance, and p2 is just { x: 4, y: 5 }.



And with the toPlainObj method:



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);
}
}


If this is something you need in more classes then you can have a base class which has this method:



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;
}
}

[#62121] Monday, May 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
catrinas

Total Points: 587
Total Questions: 100
Total Answers: 105

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;