In TS, the default access level for a class member is public
unless anything else is specified. Even so, is it considered a best-practice to use the public
modifier anyway? If nothing else to make the code more obvious?
In TypeScript it's public, obviously. If you happen to be using C# and TypeScript in the same project, or just in parallel, I would recommend going with explicit access modifiers, just for the sake of clarity.
TypeScript provides three access modifiers to class properties and methods: private , protected , and public . The private modifier allows access within the same class. The protected modifier allows access within the same class and subclasses. The public modifier allows access from any location.
TypeScript has two access modifiers – public and private. By default the members are public but you can explicitly add a public or private modifier to them.
In Typescript, by default, the visibility of all properties or methods in Typescript classes is “public“. A method with which is public can be accessed from anywhere, it has no restrictions.
This is a strongly subjective topic to which no perfect answer exists, IMO. However, I'd say a strong factor in settling on an answer is whether you are using other languages in parallel, and if there is a difference in default accessor modifiers between TypeScript and those other languages.
Take C#, for example. In C#, every property and field without an explicit access modifier is private. In TypeScript it's public, obviously.
If you happen to be using C# and TypeScript in the same project, or just in parallel, I would recommend going with explicit access modifiers, just for the sake of clarity.
I personally, do like to list it every time. Of course it's just a matter of personal preference. If you do want to, and you use tslint, there is an option to force explicit visibility every time.
member-access: true
As other answers have stated, this is a matter of preference (I prefer the leaner version).
If you use parameter properties though, the explicit public
access modifier is compulsory in order to create and initialize an instance member from the given parameter.
class Octopus {
readonly numberOfLegs: number = 8;
constructor(public name: string, ink: boolean) { }
}
const o = new Octopus("Lui", true)
o.name // works
o.ink // error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With