I'm trying to use classes as input values to a registry method where the return value is a cached instance of that instance. However I do not find a way to make this type safe.
What I want is something like this:
class MyRegistry {
getInstance<T, C extends Class<T>>(cls: C): T;
}
let x: MyThing = registry.getInstance(MyThing);
Is there a way to make this work? I'm aware there are ways to type out newables but I cannot find a way to make the return value concrete.
Your parameter type should describe constructor of the Class you are passing as a param. This can be achieved using the generic interface:
interface Class<T> {
new (...args: any[]): T;
}
class MyRegistry {
getInstance<T>(param: Class<T>): T {
// do your magic
}
}
You can see it in work here.
In case you need to use subclass C, that is of course easily extendable with:
class MyRegistry {
getInstance<T, C extends T>(param: Class<C>): T {
// do your magic
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With