I'd like to get the type of a TypeScript class
constructor function. In my simple attempts it is always generic Function
and not the actual constructor with the parameters as I'd expect.
class BufferedController {
constructor(id: number) {
this.id = id
}
static defaultBufferSize = 100 as const
id: number
}
// ?? Just generic Function not the actual constructor
type instanceConstructor = BufferedController["constructor"]
// Class type
type C = typeof BufferedController
// This works fine to get other static properties from the class
type n = C["defaultBufferSize"]
// ?? Also generic Function not the actual constructor
type c = C["constructor"]
What is the correct way to get the type of the constructor function from the class
? I'd like to end up with a type like constructor(id: number) => BufferedController
CodePudding user response:
I think I've got what you want. We'll write a type that gets ONLY the construct signature like this:
type CtorType<T> = T extends { new (...args: infer Args): infer Ret } ? { new (...args: Args): Ret } : never;
A class constructor certainly extends just a construct signature, so we take the arguments and inferred return type and create a new construct signature.
It's the same construct signature in the class constructor except it doesn't have anything else like static members.
Then we can use it like this:
declare const ctor: CtorType<typeof BufferedController>;
ctor.defaultBufferSize // error - doesnt exist
new ctor(0);