Private "functions" in TypeScript

Is it possible to create a private "function" (method) in the TypeScript class? Suppose 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); } } 

What when compiling is converted 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 in closure, but not on the prototype? In essence, does this make the whisper function open at compile time?

+56
typescript
Jun 04 '13 at 13:41
source share
2 answers

TypeScript public / private keywords only apply to the way TypeScript validates your code - they have no effect on JavaScript output.

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

Private visibility is a design of development time; it is used during static type checking, but does not imply forced execution at runtime .... TypeScript provides encapsulation of the implementation in classes at design time (by restricting the use of private members), but cannot provide encapsulation at run time, because all properties object available at runtime. Future versions of JavaScript may provide private names that will allow private members to enforce

This has already been asked and answered here: stack overflow

Update: this old answer still gets a lot of traffic, so it’s worth noting that in addition to the language link above, the general, private and (now) protected members are described in detail in the chapter of the TypeScript class reference .

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

+64
Jun 04 '13 at 14:01
source share
β€” -

In Javascript (unlike TypeScript) you cannot have a private member function.

If you define a private function in closure, you cannot call it as an instance method in an instance of your class.

If this is what you want, just move the TypeScript function definition outside the class body.

+7
Jun 04 '13 at 13:43
source share



All Articles