Private class constructors in TypeScript #3
robinpokorny
announced in
TIL
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
While reading the TypeScript class documentation, I noticed that it is possible to mark any class member as private (or protected). And I wondered whether a constructor could be private, too. It turns out it can, and there is a valid use case for it!
First, what does a private constructor look like? Like this!
As you can see, it's impossible to create a new instance of the class.
So, how is that useful? That class is basically worthless, right? Eeh, no!
The secret lies in the second part of the error message: ‘only […] within the class declaration’.
A little bit surprisingly to me, that also includes static methods. So you can create a class with explicit creation types.
An example would be a reimagination of the
Date
object, which is notoriously tricky:Now, I can clearly see some benefits in some use cases. It's a nice pattern to remember.
Oh, and of course, none of that limitation exists when the class is accessed from JavaScript. Be careful!
Beta Was this translation helpful? Give feedback.
All reactions