In my Typescript class, I have four properties defined like so:
class MyClass {
private x: number;
private y: number;
private z: number;
private w: number;
}
I am looking to create individual functions that will increment each of these properties:
incrementX() { this.x++; }
incrementY() { this.y++; )
...
However, I want to avoid duplicating the increment logic (++
) and instead consolidate it into a single function. If Typescript supported passing by reference like C#, I would handle it in this manner:
incrementX() { this.increment(ref this.x); }
increment(p: ref number) { p++; }
Since Typescript does not offer pass by reference, I have resorted to a less type-safe solution:
incrementX() { this.increment("x"); }
increment(p: string) {
const self = this as any;
self[p]++;
}
This method is not completely type-safe. Despite adding a runtime check to ensure self[p]
is a number, there is still room for error when calling increment('not-a-property')
. Is there a more type-safe approach to tackle this issue?
Please note that although the example uses numbers, my actual code involves operations on a different class type.