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

前端 未结 4 1851
一个人的身影
一个人的身影 2020-12-16 10:30

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 publi

相关标签:
4条回答
  • 2020-12-16 11:08

    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.

    0 讨论(0)
  • 2020-12-16 11:08

    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
    
    0 讨论(0)
  • 2020-12-16 11:22

    The upside to explicitly stating a public access modifier is that it shows you thought about it and that you decided that it should be public. The downside is that extra syntax adds noise, which makes it harder for the important code to shine through (and it's more work for the developer to have to add that extra syntax every time).

    I have seen a good few occasions where the private modifier should have been added but where access modifiers weren't taken into consideration.

    To be honest, it would have been better if everything was private by default, and you would have to add public to open it up to the outside world.

    Personally, I lean towards explicitly adding them.

    However, I think for things that have to be public it's okay to use the default (since we don't have to think about whether it should be private or not, because it has to be public).

    Examples (for Angular) are things like: @Input(), @Output(), @HostListener, and implemented public methods.

    0 讨论(0)
  • 2020-12-16 11:27

    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
    
    0 讨论(0)
提交回复
热议问题