00

It is unnecessary to specify public modifier for TypeScript class members

Sunday, December 1, 2019

TypeScript class members have three possible access modifiers: public, protected and private. Let's quickly breakdown each of these.

The public access modifier signals to the TypeScript compiler that the class member (property or method) is publicly accessible. This means that the property or method can be accessed from within the class instance, within derived class instances, and also from executing code that has a reference to the class instance.

The private access modifier signals to the TypeScript compiler that the class member is private to the class. This means that the property or method can only be accessed from within the class instance.

The protected access modifier signals to the TypeScript compiler that the class member is protected to this class and all derived class. Derived classes are those that extend the parent class.

The public access modifier is the default value in TypeScript, therefore it is unnecessary to include the public access modifier.

Instructions

Avoid

explicitly including the public access modifier for class members

Consider

remove unnecessary public access modifier

Code Examples

Remove public access modifier becuase class members are default by public

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <h1>
          Hello from lookout.dev!
        </h1>
      </div>
    );
  }
}

The public access modifier is unecessary for the render() method

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }

  public render() {
    return (
      <div>
        <h1>
          Hello from lookout.dev!
        </h1>
      </div>
    );
  }
}
Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️