Sub topic 6
Constraining to Constructor Types
This chapter assumes you can write generic functions with extends constraints, know the difference between a class and an instance of it, and have seen typeof used in a type position. Earlier chapters covered constraints on object shapes and on keys. Here the constraint describes something you can call with new.
Why classes need their own type
A class declaration creates two things with the same name: a type for its instances and a value, the constructor function. They have different types.
class Point {
x = 0;
y = 0;
}
const a: Point = new Point(); // Point is the instance type
const b: typeof Point = Point; // typeof Point is the constructor typeSuppose you want a function that receives a class and builds an object from it. The parameter cannot be typed T, because T would describe an instance. It cannot be object either, because object has no construct signature, so TypeScript will not let you write new on it. You need a type that says "something you can call with new, and the result is a T".
The construct signature
A construct signature looks like a function type with new in front:
type Constructor<T = object> = new (...args: any[]) => T;
function createInstance<T>(ctor: Constructor<T>): T {
return new ctor();
}
class Point {
x = 0;
y = 0;
}
const p = createInstance(Point); // type: PointThree parts matter here:
newmarks the type as constructible. Without it,(...args: any[]) => Tdescribes an ordinary function, andnewon it fails....args: any[]says the constructor accepts any parameters. This is the one place whereanyis the conventional choice. It lets classes with any constructor signature match.T = objectis a default type parameter. WritingConstructorwith no argument means "any constructor that produces an object".
TypeScript infers T by matching the class against the signature. It sees that Point constructs a Point, so T becomes Point.
Constraining what the constructor produces
Constructor<T> accepts any class. Often you want only classes whose instances have certain members. Put the constraint on T, exactly as with any other type parameter.
type Constructor<T = object> = new (...args: any[]) => T;
interface Entity {
id: string;
}
function createEntity<T extends Entity>(ctor: Constructor<T>): T {
const entity = new ctor();
console.log(`created entity ${entity.id}`);
return entity;
}
class Order implements Entity {
id = "order-1";
total = 0;
}
class Point {
x = 0;
y = 0;
}
const order = createEntity(Order); // type: Order
// createEntity(Point); // Error: Point has no property 'id'The constraint works in two directions. Inside the body, entity.id is allowed because T extends Entity. At the call site, a class whose instances lack id is rejected, because inference gives T = Point and Point does not satisfy Entity.
Constraining the constructor itself
There is a second way to write this. Instead of constraining the instance type, constrain the type of the class value:
type Constructor<T = object> = new (...args: any[]) => T;
function logName<C extends Constructor>(ctor: C): C {
console.log(ctor.name);
return ctor;
}
class Counter {
static created = 0;
constructor() {
Counter.created += 1;
}
}
const Same = logName(Counter);
console.log(Same.created); // static member is still visibleThe two forms differ in what they keep:
| Form | What `T` or `C` stands for | Static members kept? | Typical use |
|---|---|---|---|
| `Constructor<T>` | The instance type | No, only the instance is named | Factories, registries, type guards |
| `C extends Constructor` | The whole class value, `typeof Counter` | Yes | Mixins, decorators, wrappers that return the class |
When a function returns the class itself, use the second form. With Constructor<T> the return type would be Constructor<Counter>, and .created would no longer type-check.
Forwarding constructor arguments
any[] makes the signature accept every class, but it throws away argument checking. A factory that forwards arguments can capture the parameter list in a second type parameter.
function create<A extends any[], T>(
ctor: new (...args: A) => T,
...args: A
): T {
return new ctor(...args);
}
class User {
constructor(
public name: string,
public age: number,
) {}
}
const user = create(User, "Ada", 36); // type: User
// create(User, "Ada"); // Error: expected 3 arguments, but got 2
// create(User, "Ada", "36"); // Error: string is not assignable to numberHere A is constrained to be an array type, so it can be used as a rest parameter. TypeScript infers A as [name: string, age: number] from User, and then checks the extra arguments against it.
The standard library offers two utility types for the same job when you already have a class type in hand:
class User {
constructor(
public name: string,
public age: number,
) {}
}
type UserArgs = ConstructorParameters<typeof User>; // [name: string, age: number]
type UserInstance = InstanceType<typeof User>; // User
const args: UserArgs = ["Ada", 36];
const user: UserInstance = new User(...args);Both take the constructor type, so you write typeof User, not User.
Mixins
Mixins are the best-known use of constructor constraints. A mixin is a function that takes a class and returns a new class that extends it.
type Constructor<T = object> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
createdAt = new Date();
};
}
class User {
constructor(public name: string) {}
}
const TimestampedUser = Timestamped(User);
const u = new TimestampedUser("Ada");
console.log(u.name); // "Ada"
console.log(u.createdAt instanceof Date); // trueThis only works because of the C extends Constructor form. TBase is typeof User, so the returned class extends the real User. The result keeps the name property and the constructor parameter name: string. TypeScript requires a mixin's base to have a constructor type with a single rest parameter of type any[]. That requirement is why the signature in Constructor is written that way.
Type guards with `instanceof`
A constructor parameter also lets you write a reusable type guard:
type Constructor<T = object> = new (...args: any[]) => T;
function isInstance<T>(value: unknown, ctor: Constructor<T>): value is T {
return value instanceof ctor;
}
const values: unknown[] = [new Date(0), "text", 42];
for (const v of values) {
if (isInstance(v, Date)) {
console.log(v.toISOString()); // v is narrowed to Date
}
}Built-in classes such as Date and Map work because their constructor types have construct signatures that match.
Abstract classes
An abstract class cannot be instantiated, so typeof Shape does not match new (...args: any[]) => T. TypeScript 4.2 added abstract construct signatures for this case:
type AbstractConstructor<T = object> = abstract new (...args: any[]) => T;
abstract class Shape {
abstract area(): number;
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
function className<T extends Shape>(ctor: AbstractConstructor<T>): string {
return ctor.name;
}
console.log(className(Shape)); // "Shape"
console.log(className(Circle)); // "Circle"Every concrete class also matches an abstract construct signature. The reverse does not hold, so use AbstractConstructor only when you do not need to call new. A function that does call new must take the concrete Constructor.
Gotchas
Required constructor parameters and `new () => T`
If you write the narrower signature new () => T, a class whose constructor has required parameters does not match:
class Needs {
constructor(public name: string) {}
}
function build<T>(ctor: new () => T): T {
return new ctor();
}
// build(Needs); // Error: 'Needs' constructor requires 1 argumentUse new () => T when you really call new ctor() with no arguments and want the compiler to refuse classes that need some. Use any[] or the forwarding form when you do not mind.
Structural matching, not "is a class"
Constructor types are matched by shape. Anything with a compatible construct signature is accepted, including a hand-written object:
type Constructor<T = object> = new (...args: any[]) => T;
declare const Fake: { new (): { id: string } };
declare function make<T>(ctor: Constructor<T>): T;
const made = make(Fake); // type: { id: string }Constructor cannot tell a real class from any other value with a construct signature, and it does not need to. The same is true of everything else in TypeScript's structural system.
Interfaces are not constructors
An interface name such as Entity is only a type. There is no value to pass. If a caller wants to supply "a way to make an Entity", ask for a constructor type, or for a factory function () => T. A factory function is often the simpler choice, since it also accepts closures and does not require a class.
Private and protected constructors
A class with a private or protected constructor does not match a public construct signature, so createInstance(Singleton) fails. This is usually the behavior you want, because the class author has forbidden outside construction.
Overloaded constructors
When a class has several overloads, inference against new (...args: A) => T picks the last overload. For create above, A would then reflect only that overload. If you need a specific overload, write its parameter list explicitly instead of inferring it.
Choosing a form
- Use
Constructor<T>when you need to produce instances and only care about the instance type. - Add
T extends Somethingwhen the function body reads members of the instance. - Use
C extends Constructorwhen you return or wrap the class and the caller still needs its statics. - Use
new (...args: A) => TwithA extends any[]when you forward arguments and want them checked. - Use
abstract newonly when you never callnewon the value.
Exercise
You write function make<T>(ctor: Constructor<T>): T { return new ctor(); } with type Constructor<T = object> = new (...args: any[]) => T. A colleague calls make(Config), where Config is a class with constructor(path: string). Does this compile, and what does it do at runtime? How would you make the compiler catch the problem?
Show answer
It compiles, because any[] accepts every parameter list. At runtime new ctor() runs with no arguments, so path is undefined and the class may fail or misbehave. To catch it, either type the parameter as new () => T, which rejects classes that require arguments, or use create<A extends any[], T>(ctor: new (...args: A) => T, ...args: A) so callers must pass the correct arguments.
Exercise
Write a mixin Tagged that adds a tag = "default" property to any class, and explain why it must be declared as Tagged<TBase extends Constructor>(Base: TBase) rather than Tagged<T>(Base: Constructor<T>) if the result must keep the base class's static members.
Show answer
function Tagged<TBase extends Constructor>(Base: TBase) { return class extends Base { tag = "default"; }; }. With TBase extends Constructor, TBase stands for the full class value, such as typeof User, so the returned class type includes the base's static members and constructor parameters. With Constructor<T>, only the instance type T is captured. Static members are not part of that type, so they are lost from the result.
Exercise
Why does createInstance(Shape) fail when Shape is abstract and createInstance takes Constructor<T>, and what changes if the parameter type is AbstractConstructor<T>?
Show answer
An abstract class has no ordinary construct signature, so typeof Shape does not match new (...args: any[]) => T. With abstract new (...args: any[]) => T the argument is accepted, but the function body can no longer call new ctor() on it. That is why the abstract form is for inspecting or extending a class, not for instantiating it.