I'm trying to set dynamically a property to a class in TypeScript:
class Foo {
a: number;
b: number;
c: string;
d: AnotherType
e: Function;
constructor(a: number, b: number) {
this.a = a;
this.b = b;
//...
}
get sum(): number {
return this.a + this.b;
}
get name(): string {
return `My name is ${this.c}`;
}
public updateProperty(
prop: keyof Foo,
value: number,
) {
this[prop] = value;
}
}
But I'm getting two errors:
- TS2540: Cannot assign to 'sum' because it is a read-only property.
- TS2322: Type 'number' is not assignable to type 'number & ((prop: keyof Foo, value: number) => void)'.
Type 'number' is not assignable to type '(prop: keyof Foo, value: number) => void'.
I understand that the first error is because I cannot redefine sum
, and the second error is because updateProperty
is a function, so I shouldn't redefine it.
Is there a way that I can create a type for prop
that resolves to: "all the class members that aren't getters or instance methods"?
This answer talks about a property that has a type, but in this example, Foo
only has number
, and it should work, but if won't work if a
is a string
, also it won't fix the getter case.
This answer tries to apply a snapshot of a partial record to this, but that will cause a circular dependency and will fail