I have a class with a number of private properties with various types for which I want to create one generic public Set method.
class A {
private prop1: Array<A> = new Array()
private prop2: Array<[A,A]> = new Array()
}
// Set method that can be used in following way:
// a.Set('prop1', new Array<A>())
// a.Set('prop2', new Array<[A, A]>())
// but not:
// a.Set('prop3', ...)
// a.Set('prop1', 23)
Essentially, I want a Set method that has: The first parameter restricted to a set of private properties of A
. Ideally automatically enumerated but since keyof
doesn't handle private properties a handwritten set is fine (e.g. type AProps = 'prop1'|'prop2'
). The second parameter restricted to the type of the property corresponding to the first parameter.
I.e. something like this (I know this doesn't work) where PropType<A, property>)
selects correct dependent type of of union of all possible PropType
s of A
:
type PropType<TObj, TProp extends keyof TObj> = TObj[TProp];
class A {
private prop1: Array<A> = new Array()
private prop2: Array<[A,A]> = new Array()
public Set(property: keyof A, value: PropType<A, property>) {
this[property] = value
}
I'm 90 % sure it can't be done within current TS typesystem in a reasonably typesafe manner.
While decorator might be helpful, it's not (yet) usable due to inability to modify target's class/interface: https://github.com/microsoft/TypeScript/issues/4881
I know that I can create the setter methods by hand. I also know that I can create one that will use a trick similar to this. I'm not asking about that. I know there're many workarounds.