Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure underscore functions and variables are private

Is it possible to set a rule whereby functions/variables in a class that have a leading underscore should be marked private?

For example

_myFunc () {}         // fail
private _myFunc () {} // pass

Similarly

_myVar: string = ''         // fail
private _myVar: string = '' // pass

There is an example in the docs that specifies any private member has to start with an underscore, but there is nothing mentioned about the inverse - underscore member has to be private.

like image 434
abyrne85 Avatar asked Aug 31 '25 01:08

abyrne85


1 Answers

I've managed to get this with the following config, using the @typescript-eslint/naming-convention rule:

  • firstly, forbid the leading underscore for all class members.
  • secondly, require a leading underscore only for private class members.
rules: {
  // ...
  "@typescript-eslint/naming-convention": [
     "error",
     {
       "selector": "memberLike",
       "format": ["camelCase"],
       "leadingUnderscore": "forbid"
     },
     {
       "selector": "memberLike",
       "modifiers": ["private"],
       "format": ["camelCase"],
       "leadingUnderscore": "require"
     }
   ]
}

Example:

_fooFunc () {}          // fail
private barFunc () {}   // fail  
private _bazFunc () {}  // pass


_fooVar = '';           // fail
private barVar = '';    // fail
private _bazVar = '';   // pass

Eslint output:

error  Class Method name `_fooFunc` must not have a leading underscore     @typescript-eslint/naming-convention
error  Class Method name `barFunc` must have one leading underscore(s)     @typescript-eslint/naming-convention

error  Class Property name `_fooVar` must not have a leading underscore    @typescript-eslint/naming-convention
error  Class Property name `barVar` must have one leading underscore(s)    @typescript-eslint/naming-convention
like image 91
andreivictor Avatar answered Sep 03 '25 05:09

andreivictor