Richard Richard - 22 days ago 7
TypeScript Question

Private "functions" in 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?

Answer

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: http://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.

Comments