I need to pass a class reference as a function parameter and invoke a static method on this class. In the future, I might need to create an instance of the class and added a constructor as example.
I have it working without typings:
class Messages {
getMessage(classRef: any): any {
return classRef.getMessage()
}
}
class myClassA {
constructor(public id: number, public message: string) {}
static getMessage(): string {
return 'hello from class A';
}
}
class myClassB {
constructor(public id: number, public message: string) {}
static getMessage(): string {
return 'hello from class B';
}
}
var messages = new Messages();
var messageA = messages.getMessage(myClassA);
var messageB = messages.getMessage(myClassB);
console.log(messageA) // 'hello from class A'
console.log(messageB) // 'hello from class B'
I am trying to type the class reference, possibly with generics but confused about how to go about this.
I tried doing something along the lines of getMessage<C>(classRef: {new(): C;}): any {}... but none of that is working.
Can someone please explain how I can pass a class reference properly?