Is it possible to extract the instance type from the instantiable type?

Viewed 51
class ClassOne {
  property1 = true;
}

type Instantiable = { new(...args: any[]): ClassOne };

Is it possible to extract the ClassOne directly from the Instantiable type? If that's the case, then how?

1 Answers

TypeScript provides a utility type called InstanceType. You can use it like this:

class ClassOne {
  property1 = true;
}

type Instantiable = { new(...args: any[]): ClassOne };

type T = InstanceType<Instantiable>;

TypeScript Playground

Under the hood it uses the infer keyword within a conditional type:

type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any

Further reading

Related