It is unnecessary to specify public
modifier for TypeScript class members
Sunday, December 1, 2019
It is unnecessary to specify public
modifier for TypeScript class members
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
explicitly including the public
access modifier for class members
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>
);
}
}
Have a question or comment?