Encountered a problem with intersection types in TypeScript...
There are three type aliases:
Prototype<T>
- representing an object or class with aprototype
property.DefaultCtor<T>
- representing an object or class with a default constructor.ParameterizedCtor<T>
- representing an object or class with a parameterized constructor.
Experimented with the following intersection combinations:
- functioning correctly.Prototype<T> & DefaultCtor<T>
- encountering a compiler error.Prototype<T> & ParameterizedCtor<T>
Example
type Prototype<T> = {
prototype: T;
}
type DefaultCtor<T> = {
new(): T;
}
type ParameterizedCtor<T> = {
new(...args: any[]): T
}
function makeDefault<T>(ctor: Prototype<T> & DefaultCtor<T>): T {
return new ctor();
}
function makeWithArgs<T>(ctor: Prototype<T> & ParameterizedCtor<T>, ...args: any[]): T {
return new ctor(...args);
// ERROR: Cannot use 'new' with an expression whose type lacks a call or construct signature.
}
Test it out in the Playground
Error The issue arises with the
Prototype<T> & ParameterizedCtor<T>
intersection:
Cannot use 'new' with an expression whose type lacks a call or construct signature.
Questioning why the TypeScript compiler can determine the presence of a constructor in the
Prototype<T> & DefaultCtor<T>
intersection type, but not in the Prototype<T> & ParameterizedCtor<T>
intersection type?