Private “functions” in TypeScript

Update. Private methods using # are now implemented. See here: https://github.com/microsoft/TypeScript/pull/42458

TypeScript public/private keywords only apply to the way TypeScript checks your code – they don’t have any effect on the JavaScript output.

According to the language specification (pp. 9-10):

Private visibility is a design-time construct; it is enforced during
static type checking but does not imply any runtime enforcement.

TypeScript enforces encapsulation of implementation in classes at
design time (by restricting use of private members), but cannot
enforce encapsulation at runtime because all object properties are
accessible at runtime. Future versions of JavaScript may provide
private names which would enable runtime enforcement of private
members

This has already been asked and answered here: https://stackoverflow.com/a/12713869/1014822

Update: This old answer still gets an amount of traffic, so worth noting that, in addition to the language spec link above, public, private, and (now) protected members are covered in detail in the TypeScript handbook chapter on classes.

2018 Update
Implementation of ES Private Fields is now a Future item on the TypeScript RoadMap although discussion suggests this will be a parallel hard private option, not a replacement for the current soft private implementation.

2020 Update
Runtime private fields using the # operator have been implemented as of TS 3.8. There is a good discussion of how they work and how they differ from compile-time fields with the private keyword on StackOverflow here.

Private methods have reached stage 3 of the TC39 working group. The feature is currently in active discussion for TypeScript, for example here.

Leave a Comment