1

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.

hkonsti
  • 85
  • 1
  • 1
  • 6
  • I don't think this is possible. also, it's a bad idea because it violates the Liskov Substitution Principle https://stackify.com/solid-design-liskov-substitution-principle/ – M.Elkady Jul 04 '19 at 18:44
  • @M.Elkady it doesn't violate the Liskov Substitution Principle because using the accepted answer the method isn't accessible from outside in both cases (which is what I needed) and therefore doesn't change the behavior of the class – hkonsti Jul 04 '19 at 20:09

2 Answers2

3

The keyword protected makes the method accessible only to extended classes and not to the outside.

class BaseClass {
    constructor() { }

    protected sayHello() {
        console.log('hello');
    }
}

class Class extends BaseClass {
    constructor() {
        super();
    }

    protected sayHello() {
        super.sayHello(); 
    }
}
Kevin Pastor
  • 761
  • 3
  • 18
1

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
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357