Answer a Question
Sign In

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

Avoid

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>
    );
  }
}

Do

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>
    );
  }
}
Brian Love
Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.
Google Developers Expert

Whoa 🤚 You need to sign in to join the discussion.

Don't worry, if you start a comment, we'll save it for when you return. 😉