Private keyword vs # in TypeScript

I recently (I’m not a hardcore JS/TypeScript developer) find out that you can make things private in two different ways in TypeScript, by using the private keyword, or by prefixing method or field with a #. The latter is truly private in the ECMAScript world, where the private keyword is only inaccessible from a TypeScript perspective.

Should there be a rule to prefer one of the two? And if so, in which cases? I noticed already that you can not chain methods that use the # prefix, so the following can not be changed:

class Parser {
   
    public parse(): string | undefined {
        return this.email()?.result;
    }

    private email(): Parser | undefined {
        return this
            ?.displayName()
            ?.mailto()
            ?.stripComment()
            ?.local()
            ?.domain();
    }
}

But in other cases it might be better to use the # as that is truly private?!

I’m really interested what others think: does it matter, and if so, which one is preferable and why?

4 Likes

Anyone (preferably for Sonar) with remarks on this one?

Hello @Corniel,

sorry for the late response. We discussed this internally and it makes sense to consider this for a rule. We still need to check what would be the Sonar recommendation, and for that we need to investigate internally how Typescript deals with private when transpiling to js using all different targets and if it has any effect in the output. But yes this is a very valid idea.

I created a ticket to track this.

Thanks!
Victor

1 Like