After considering this response, it is evident that utilizing a reference type such as an object or array instead of a primitive value type like a number can significantly enhance your experience. By introducing an extra layer of indirection (e.g., transforming someVar = 123
into someVar = {value: 123}
), achieving similar functionality to your requirements becomes quite feasible.
In situations where your specific usage necessitates an object's property to directly mimic a reference to a primitive value stored elsewhere, you can achieve this behavior by implementing the property as a getter and setter pair. While more complex, this approach will deliver the desired outcome.
Here is an example:
class MyService {
someVariableA = 1;
someParams: {
someVariableB: number;
otherVariable: number;
};
constructor() {
this.someVariableA = 1;
const that = this;
this.someParams = {
someVariableB: 2,
get otherVariable() {
return that.someVariableA
},
set otherVariable(val: number) {
that.someVariableA = val;
}
}
}
}
It is important to note that for the otherVariable
getter and setter to access the correct context, the code had to be moved into the constructor with this
being copied into a new variable named that
. The this
context within a getter/setter pertains to the object it belongs to rather than any outer scope's this
.
To confirm its effectiveness:
const ms = new MyService();
ms.someVariableA = 100;
console.log(ms.someParams.otherVariable); // 100
ms.someParams.otherVariable = -5;
console.log(ms.someVariableA); // -5
Apparent from the outcomes; alterations in ms.someVariableA
are promptly reflected in ms.someParams.otherVariable
, and vice versa. Best of luck with implementing these changes!
Playground link to showcased code