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?

2
  • Does this answer your question? How to call a parent method from child class in javascript? Commented Oct 1, 2020 at 9: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. Commented Oct 1, 2020 at 9:09

1 Answer 1

6

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()

Sign up to request clarification or add additional context in comments.

2 Comments

foo should be static I think
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.