microsoft / microsoft/TypeScript
ConstructorParameters is not working for private constructors (and protected constructors)
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript 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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Begin with the linked Playground reproduction and the TypeScript 3.4 behavior for ConstructorParameters applied to private and protected constructors. Identify the relevant compiler and regression-test entry points, then establish behavior that infers the constructor argument tuple without weakening visibility checks; done means the example type-checks with the expected tuple and coverage prevents regressions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100