I want to make an inherited method private outside of the extended class in Typescript
Let's say I have two classes like this:
class BaseClass{
constructor(){}
sayHello(){
console.log('hello');
}
}
class Class extends BaseClass{
constructor(){
super();
}
private sayHello(){ //I don't want to have to do this every time
super.sayHello();
}
}
let obj = new Class();
obj.sayHello();
I need to access the method sayHello()
inside of 'Class' but it shouldn't be accessible from outside. I don't want to have to overwrite it every time I inherit.
I think you are looking for the protected
access modifier. A protected member is accessible from derived classes but not from outside the class
class BaseClass{
constructor(){}
protected sayHello(){
console.log('hello');
}
}
class Class extends BaseClass{
constructor(){
super()
this.sayHello() // ok
}
}
let obj = new Class();
obj.sayHello(); //err