In my programming project, I have a base class called GenericSetting
that is subclassed in approximately 10 or more types.
export class GenericSetting {
configuration: SettingArgs
constructor(args: SettingArgs) {
this.configuration = args
}
}
As you can see, it also receives arguments which are subclassed themselves to include additional properties required by the subclasses.
I then proceed to create hundreds of settings, keeping them as concise as possible.
FocusPos = new LensValuedSetting({ componentId:LensModule, key:"Focus-ActuatorPosition", displayName:"@{ActuatorPosition}", categories:["@{Lens}", "@{Focus}"], mode:EditMode.ReadOnly, stepSize:0, ctx:{ canId:7, dataType:"UInt16", bit:-1, startByte:2, rounding:1 }})
FocusAuxActive = new LensValuedSetting({ componentId:LensModule, key:"Focus-AuxInputDeviceActive", displayName:"@{AuxInputDeviceActive}", categories:["@{Lens}", "@{Focus}"], mode:EditMode.ReadOnly, stepSize:0, ctx:{ canId:36, dataType:"Byte", bit:1, startByte:6, rounding:1 }}, )
FocusAuxPos = new LensValuedSetting({ componentId:LensModule, key:"Focus-AuxInputDevicePosition", displayName:"@{AuxInputDevicePosition}", categories:["@{Lens}", "@{Focus}"], mode:EditMode.ReadOnly, stepSize:0, ctx:{ canId:36, dataType:"Int16", bit:-1, startByte:2, rounding:1 }}, )
The issue arises because TypeScript infers the arguments passed, making the args
argument of type object
at runtime, bypassing the constructors of all these subclassed setting arguments.
To address this, I considered creating the type being type-guarded in TypeScript within the base constructor and using Object.assign()
like so:
export class GenericSetting {
configuration: SettingArgs
constructor(args: SettingArgs) {
const typedArgs = new <HOW DO I GET CTOR OF ARGS TYPE?>
Object.assign(typedArgs, args)
this.configuration = typedArgs
}
}
However, since I lack information about the type-guarded/inferred type at runtime, is there no way to achieve this in one place? Must I write this logic in every subclass?