I have a class that represents a configurable object, e.g.
class Device {
// ... code that manipulates the device
}
This device in turn can have services. Services are preferably known in compile type, but they have to be determined in initialisation of Device. I want to be able to access a service if it is available, for example:
const device = new Device(new ControlService())
typeof device.control // = ControlService
//But
const device2 = new Device()
device.control // Compilation error because this device doesn't have the service.
Is there a way to achieve this with generics in TypeScript 4.0 and above?