Support for both public and protected constructor overload signatures
See original GitHub issueSuggestion
TypeScript already supports abstract class, which cannot be instantiated (of course, I know they can — it’s just the compiler that disallow that). Non–abstract classes, on the other hand, can be instantiated using any constructor overload they provide.
There are cases, however, when you may want to allow creation of a class using only one constructor overload and provide another one for subclasses to use. The latter is what I would call “protected constructor,” which could be defined with the addition of the modifier protected
. However, it looks like TypeScript currently doesn’t support overloads with different access modifiers; I wonder why, as signature matching is merely a static check and doesn’t change the way the method is actually invoked. If different overload signatures were allowed to support different access modifiers, the scenario with a protected constructor and a public one I described would be permitted.
🔍 Search Terms
protected constructor abstract constructor
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
⭐ Suggestion
Just allow having different access modifiers for different overload signatures. There’s no need I can see to disallow that and it wouldn’t be difficult at all to implement.
📃 Motivating Example
Suppose I want to use the composition pattern and provide default sub–instances in the public constructor but still allow subclasses to pass their own sub–instances, as follows:
class Controller {}
class View {
constructor();
protected constructor(controller: Controller);
constructor(readonly controller: Controller = new Controller()) {}
}
class CustomController extends Controller {}
class CustomView extends View {
constructor() {
super(new CustomController());
}
}
💻 Use Cases
Additionally to the “protected constructor” use case I described above, since such a feature requires, as previously mentioned, allowing different access modifiers across overload signatures, this change would also permit a lot of other things. I suppose you all can understand that having protected signatures for a subclass and exposing only public signatures for other sites may turn useful.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:6 (3 by maintainers)
Top GitHub Comments
AFAIK the reasoning in #9592 is still true, but I’ll leave this open as a suggestion so people can discuss, since the old issue is locked.
It would be nice to see this feature