Model constructor-produced values
A generic API accepts a class constructor and needs to type values created from it.
TypeScript · Type Alias
InstanceType<Type> derives the instance type produced by a constructor function. For a class, pass typeof ClassName to obtain the type of objects created with new ClassName().
InstanceType<Type> derives the instance-side type produced by a constructor function. Pass a class value with typeof to describe the constructor, then use the resulting type wherever instances of that class are expected.
InstanceType<Type>| Name | Type | Description |
|---|---|---|
Type | abstract new (...args: any) => any | A type representing an abstract or concrete constructor function, constrained by abstract new (...args: any) => any. |
A type consisting of the instance type created by the constructor in Type.
InstanceType is a globally available utility type.string are rejected.Function type is not specific enough to satisfy the required constructor signature.class Point {
constructor(public x: number, public y: number) {}
}
type PointInstance = InstanceType<typeof Point>;
function moveRight(point: PointInstance) {
point.x += 5;
}
const point = new Point(3, 4);
moveRight(point);
console.log(point.x); // 8typeof Point captures the constructor value, and InstanceType derives the type of objects created by that constructor.
A generic API accepts a class constructor and needs to type values created from it.
A codebase needs an instance type without duplicating a class name in a type declaration.
A library exposes constructors and wants types to follow their concrete instance shapes.
InstanceType do, and how is it used with a class?InstanceType<Type> constructs the type of instances created by the constructor represented by Type. For a class named C, InstanceType<typeof C> evaluates to C.
Follow-up: What happens for InstanceType<any> and InstanceType<never>? They evaluate to any and never, respectively.
The type parameter is constrained to an abstract construct signature: abstract new (...args: any) => any. This ensures the supplied type represents something callable with new.
Follow-up: Why use typeof C rather than C? C is the instance type, while typeof C is the constructor value type needed by InstanceType.
InstanceType introduced, and where is it available?The utility was released in TypeScript 2.8 and is globally available as a built-in utility type. It is intended for common type transformations involving constructor functions.
Follow-up: How would you model a function that accepts a constructor and returns its instance? Use a generic constructor parameter constrained by an abstract construct signature, then apply InstanceType to that parameter.
Constructor Signaturestypeof operatorClassesReturnTypeInstance-side type