Suppose we have the following class:
class Car {
private _id!: string;
private _brand!: string;
constructor(id: string, brand: string) {
this.id = id;
this.brand = brand;
}
get id() {
return this._id;
}
set id(value) {
this._id = value;
}
get brand() {
return this._brand;
}
set brand(value) {
this._brand = value;
}
}
And that we create the following class instance
let car1 = new Car('123', 'Ford');
When accessing the properties of car1
directly everything works perfectly:
console.log(car1.id);
// 123
But when using object destructuring, this does not work:
const { id } = car1;
console.log(id);
// undefined
And when I print the object, the properties defined through get syntax also does not appear:
console.log(car1);
// { _id: '123', _brand: 'Ford' }
How can I make the get
syntax work with object destructuring? (i.e., how can I use the get
syntax (or a similar alternative) to store the properties in the instance itself and not in its prototype while mantaining the code clean?)
I have read about Object.defineProperty
, but I find it very cumbersome to use it in every class I want to define. Are there any other alternatives or ways to achieve this? Thank you in advance!