ConstructorParameters is not working for private constructors (and protected constructors)
See original GitHub issueTypeScript Version: 3.4 Search Terms: ConstructorParameters, private constructor
Code
class Foo
{ public constructor(a: number, b: boolean, c: string) { } }
class Bar
{ private constructor(a: number, b: boolean, c: string) { } }
type FooCtorArgs = ConstructorParameters<typeof Foo>;
type BarCtorArgs = ConstructorParameters<typeof Bar>;
Expected behavior:
BarCtorArgs
is [number, boolean, string]
.
Actual behavior:
Error in line 8:
Type 'typeof Bar' does not satisfy the constraint 'new (...args: any) => any'. Cannot assign a 'private' constructor type to a 'public' constructor type.
Use Case
Convenient factory pattern to mimic asynchronous object construction.
class Component
{
public static async create(...args: ConstructorParameters<typeof Component>)
{
const component = new Component(...args);
await component.initialize();
return component;
}
private constructor(a: number, b: boolean, c: string)
{ /* stuff */ }
private async initialize()
{ /* asynchronous setup */ }
}
Ideas for Solution
Allow visibility modifiers in interfaces. Yes, if you use an interface to outline the visible properties of an object to a user this makes no sense, but why not allow interfaces to be a flexible tool to specify internal rules of implementations? I think this problem could be solved, if the ConstructorParameters
type could be defined like the following:
type ConstructorParameters<T extends {private new (...args: any[]): any}> = T extends new (...args: infer P) => any ? P : never;
Which is of course no allowed at the moment.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:34
- Comments:11
Top GitHub Comments
With some hacks this works and is quite short:
You are correct, that works great!