I tried to map classes to strings. Something like:
map.add(ClassName, 'my string');
for this I created a custom type:
type NoConstructor<T> = Pick<T, keyof T>;
then I define a map likes this:
const map: Map<NoConstructor<typeof Device>, string> = new Map();
while map.add(ClassName, 'my string'); works, map.get(instanceOfClassName.constructor) only works as long as a class has no static methods. As soon as a class has static methods, I get an error by TypeScript:
Argument of type 'Function' is not assignable to parameter of type 'NoConstructor'. Type 'Function' is missing the following properties from type 'NoConstructor': getInputs, getOutputs
Why do static methods on the class influence my custom type? To me this doesn't make sense. Can anyone elaborate why this is the case and how to fix this code example?
Example on typescriptlang.org/play:
export abstract class Device {
public getStatus(): string {
return 'foo';
}
// Remove this one
public static getInputs(): {[key: string]: number} {
return {};
}
// and remove this one, and the code works
public static getOutputs(): {[key: string]: number} {
return {};
}
}
class DeviceA extends Device {
}
type NoConstructor<T> = Pick<T, keyof T>;
export default class DeviceUpdater
{
private readonly map: Map<NoConstructor<typeof Device>, string> = new Map();
public add(deviceType: NoConstructor<typeof Device>, updater: string) {
this.map.set(deviceType, updater);
}
public update(device: Device): void {
const result = this.map.get(device.constructor);
if (result === undefined) {
throw new Error(`Cannot update device of type '${device.constructor.name}': no updater found`);
}
console.log(result);
}
}
const deviceUpdater = new DeviceUpdater();
deviceUpdater.add(DeviceA, 'something');
deviceUpdater.update(new DeviceA());