jvrnt jvrnt - 3 months ago 17
TypeScript Question

Accessing and executing function in child class from base class

Is it possible to access child class members and execute child function from base class?

For example:

class ChildClass extends BaseClass {

protected childMember = 'someName';

constructor() {
super();
super.runBaseFn();
}

runChildFn() {
console.info('child fn');
}
}

class BaseClass {

runBaseFn() {
if (child.childMember === 'someName') {
child.runChildFn();
}
}
}


Is this possible to accomplish the code in
runBaseFn
? Or any similar solution?

Answer

You'll need to declare that in the parent class:

class BaseClass {
    protected childMember: string;

    runBaseFn() {
       if (this.childMember === 'someName') {
           this.runChildFn();
       }
    }

    protected runChildFn() {}
}

class ChildClass extends BaseClass {
    constructor() {
        super();

        this.childMember = 'someName';
        super.runBaseFn();
    }

    runChildFn() {
        console.info('child fn');
    }
}

(code in playground)

You can make the parent class abstract:

abstract class BaseClass {
    protected childMember: string;

    runBaseFn() {
       if (this.childMember === 'someName') {
           this.runChildFn();
       }
    }

    protected abstract runChildFn();
}