Is there a distinction that needs to be made?
No, there isn't a difference. However, the use of InstanceType
is required in certain scenarios.
The purpose of the InstanceType
helper type is because a class name can represent two things:
- The class name as the constructor function at runtime.
- The class name as the return type of the constructor function at compile time (including the constructor function's prototype and potentially some instance fields).
In TypeScript, when you define a class
, you are defining both: the constructor function (and its type) and the type of the instances created from it (which includes the class methods and fields).
In the provided example, the declaration includes:
MyClass
: an interface that encompasses the class methods and fields.
typeof MyClass
: the constructor function (in this case referring to the runtime class).
Since no specific constructor function was specified, its type is
new () => MyClass</code, and you can obtain the type <code>MyClass
using
InstanceType
.
To illustrate with a practical scenario, envision creating a factory function (which generates instances of classes). An initial implementation might appear as follows:
declare function factory<T>(ctor: T): T;
class A { }
const res = factory(A);
// ^ resulted in `res: typeof A`, not an actual instance type.
Although TypeScript doesn't raise an error, you're essentially instructing TypeScript to interpret res
as the constructor function for A
rather than an instance of A
.
However, the following approach proves successful:
type Constructor = new (...args: any[]) => any;
declare function factory<T extends Constructor>(ctor: T): InstanceType<T>;
class A { }
const res = factory(A);
// ^ yields `res: A`, as expected.
This success is due to InstanceType
extracting the appropriate return type.
Playground