What is the purpose of the public access modifier for classes in Typescript?
What is the difference between
export class Thing {
public doStuff(){
Your sample code means exactly the same in TypeScript. When you don't put a modifier public
, private
or protected
on your member definition then TypeScript will choose the default one which is public
.
That not make sense for Javascript because TypeScript transpiler will generate exactly the same code. But those modifiers will help you to encapsulate your class members and make them :
public
private
protected
Again the generated Javascript will not contain the modifiers. That means that if someone get your Javascript code it will access to the members even if you defined them as private
. The modifiers are only helpful in TypeScript and help developers to not access some class members.
It's just an explicit way to set the method to be public
. By default all class methods / properties in TypeScript are of type public, but you can as well note this in your code for clarity.
You can read more about it in the Handbook, here is an excerpt :
Public by default
In our examples, we’ve been able to freely access the members that we declared throughout our programs. If you’re familiar with classes in other languages, you may have noticed in the above examples we haven’t had to use the word public to accomplish this; for instance, C# requires that each member be explicitly labeled public to be visible. In TypeScript, each member is public by default.
You may still mark a member public explicitly.
Two reasons for using public
, one subjective/style, the other objective:
It's in-code documentation. Leaving off an access modifier could be taken as your having forgotten it. (This is the subjective/style reason.)
If you want to use the shorthand initialization feature TypeScript adds to class constructors, you need the public
to tell TypeScript to do that.
Here's an example of #2:
class Example {
constructor(public name: string) {
// ^^^^^^---------------- This is what triggers the feature
}
}
const e = new Example("Joe");
console.log(e.name); // "Joe"
(On the playground.)