1

If I have an extended class that overrides a base class function, can I call the base class function within the extended class function? Something similar to:

class Base {

  DoSomething() {

    console.log("base class function");

  }

}

class Derived extends Base {

  DoSomething() {

    this.base.DoSomething();

    console.log("extended class function");

  }

}

The output from Derived.DoSomething() would ideally look like:

"base class function"
"extended class function"

Is this possible in TypeScript?

Flopdong
  • 259
  • 1
  • 3
  • 15
  • Does this answer your question? [How to call a parent method from child class in javascript?](https://stackoverflow.com/questions/11854958/how-to-call-a-parent-method-from-child-class-in-javascript) – A_A Oct 01 '20 at 09:00
  • The second answer to that question is what I was looking for, thanks! I skipped that post at first because the question looked sufficiently different from what I was looking for. – Flopdong Oct 01 '20 at 09:09

1 Answers1

5

Yes, you can access the parent methods via super keyword

class Base {
  foo() {
    console.log("base class function");
  }
}

class Derived extends Base {
  foo() {
    super.foo();
    console.log("extended class function");
  }
}

(new Derived()).foo()
A_A
  • 1,832
  • 2
  • 11
  • 17
  • foo should be static I think – wael32gh May 03 '23 at 10:54
  • @wael32gh For this example static would make sense, however the `console.log` is just a placeholder for more complex logic, which may require it to be non-static by accessing properties of the class instance – A_A May 08 '23 at 08:05