I have identified a problem when using intersection types in TypeScript...
I have three type aliases:
Prototype<T>
- expresses an object/class that has aprototype
property.DefaultCtor<T>
- expresses an object/class with a default constructor.ParameterizedCtor<T>
expresses an object/class with a parameterized constructor.
I have tried these intersection permutations:
Prototype<T> & DefaultCtor<T>
- works fine.Prototype<T> & ParameterizedCtor<T>
- raises a compiler error.
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.
}
Try it in the Playground
Error
The error occurs with the Prototype<T> & ParameterizedCtor<T>
intersection:
Cannot use 'new' with an expression whose type lacks a call or construct signature.
Why does the TypeScript compiler recognise the Prototype<T> & DefaultCtor<T>
intersection type as having a constructor, but not the Prototype<T> & ParameterizedCtor<T>
intersection type?
ParameterizedCtor
on its own works as well. – H.B.