Typescript classes: Is explicit 'public' modifier a best-practice?

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

Tags:

Typescript