7

is there a way to call a function from baseclass like overwrite.

Base Class

export class BaseClass {
   constructor() {
   //do something asynchronous
   //than call initialized
   }
}

Inheritance Class

export class InheritanceClass extends BaseClass {
   initialized() {
   // get called from base class
   }
}

2 Answers 2

9

Do you mean like this:

class Base {
    constructor(){
        setTimeout(()=>{
            this.initialized();
        }, 1000);
    }

    initialized(){
        console.log("Base initialized");
    }
}

class Derived extends Base {
    initialized(){
        console.log("Derived initialized");
    }
}

var test:Derived = new Derived(); // console logs "Derived initialized" - as expected.

Works well in the Playground (Ignore the odd red underline on setTimeout(), which I think is a bug - it compiles and runs fine.)

You do need the method present on Base, but you can override it in Derived (with or, as in this case, without a call to super.initialized()).

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

2 Comments

So if the base class was say Animal and the derived class was Dog you could have a walk method, but what about Snakes and Birds would you have a slither and fly method on your animal class ?
Different use case. I'm not suggesting there's no need for abstract members in TypeScript, just that this answer precisely addresses the OP's request for the ability to "do something asynchronous, then call initialized" and to "call a function from baseclass like (presume typo:) override"
2

In order to do that you would need to have initialized as an abstract member of the abstract class. typescript currently does not support this however the feature has been asked for and there is a work item open for it:

http://typescript.codeplex.com/workitem/395

4 Comments

If you want initialized to not exist on the base then it is the answer otherwise it becomes an override. Strictly speaking there are ugly ways round it but should not be encouraged.
Should not be encouraged? This is just a simple override. The OP hasn't asked for an abstract method - just the ability to override one.
Yes, breaking encapsulation and the single responsibility principal, should not be encourgaed.
I think the OP was asking if it can be done (implicitly: within the constraints of the language as it exists); you make a valid point about good OOP practice, however, so +1 from me.

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.