Is it possible to infer the constructor type of a class in TypeScript? I tried this but it seems not to work:
type Constructor<K> = K extends { new: infer T } ? T : any;
Is it possible to infer the constructor type of a class in TypeScript? I tried this but it seems not to work:
type Constructor<K> = K extends { new: infer T } ? T : any;
There is already a predefined conditional type that allows you to extract the instance type from a class type, called InstanceType
class A { private x: any}
type AInstance = InstanceType<typeof A> // same as A
The definition of this type is:
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
constructor
property. So unless you just want to get Function
, you're probably stuck with new (...args: any) => T
unless you manually strengthen the constructor
property on all the classes you care about. –
Egin Instead of trying to infer it, can you refer to class types by their constructor functions like this?
type Constructor<K> = { new(): K };
const x: Constructor<String> = String;
const s = new x();
In most cases, doing typeof ClassA
is what you need. But you can also create a util type to manually infer the constructor type
type Constructor<T extends new (...args: any) => any> = T extends new (...args: infer A) => infer R ? new (...args: A) => R : neverÏ
© 2022 - 2024 — McMap. All rights reserved.
type Constructor<K> = K extends { new: () => infer T } ? T : any;
– Gilberteclass Foo {}
,type CtorOfFoo = typeof Foo
– Eurhythmic