Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private "functions" in TypeScript

Tags:

typescript

Is it possible to create a private "function" (method) within a TypeScript class? Let's assume we have the following Person.ts TypeScript file:

class Person {     constructor(public firstName: string, public lastName: string) {     }      public shout(phrase: string) {         alert(phrase);     }      private whisper(phrase: string) {         console.log(phrase);     } } 

Which when compiled is being transformed to the following:

var Person = (function () {     function Person(firstName, lastName) {         this.firstName = firstName;         this.lastName = lastName;     }     Person.prototype.shout = function (phrase) {         alert(phrase);     };     Person.prototype.whisper = function (phrase) {         console.log(phrase);     };     return Person; })(); 

Observations

I was expecting the whisper function to be declared within the closure, but not on the prototype? Essentially this makes the whisper function public when compiled?

like image 303
Richard Avatar asked Jun 04 '13 13:06

Richard


1 Answers

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.

like image 90
Jude Fisher Avatar answered Sep 16 '22 14:09

Jude Fisher