Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class to Instance Registry Typing in TypeScript

Tags:

typescript

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.

like image 868
Armin Ronacher Avatar asked Mar 06 '26 22:03

Armin Ronacher


1 Answers

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
  }
}
like image 79
Miroslav Jonas Avatar answered Mar 10 '26 16:03

Miroslav Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!