0

I have some questions about typescript/javascript inheritance. I have the following base class (express controller router):

abstract class BaseCtrl {
  abstract model;

  // Get all
  getAll = (req, res) => {
    this.model.find({}, (err, docs) => {
      if (err) { return console.error(err); }
      res.json(docs);
    });
  };
export default BaseCtrl;

And the following class that implements that base:

import BaseCtrl from './base';
import Card from '../models/card';

export default class CardCtrl extends BaseCtrl {
  model = Card;

  getAll = (req, res) => {
    super.getAll(req, res);
  }

}

This code gives me the error:

Only public and protected methods of the base class are accessible via the super keyword

I would like to know how to call the super method. Can anyone help me?

0

2 Answers 2

2

You need to define getAll as a proper method:

abstract class BaseCtrl {
    abstract model;

    // Get all
    getAll(req, res) {
        this.model.find({}, (err, docs) => {
            if (err) { return console.error(err); }
            res.json(docs);
        });
    }
};
export default BaseCtrl;

Then, you can override it:

import BaseCtrl from './base';
import Card from '../models/card';

export default class CardCtrl extends BaseCtrl {
     model = Card;

     getAll(req, res) {
       super.getAll(req, res);
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Matias! Thanks for you answer! Do you know how can I get this code working with the routes.route: router.route('/cards').get(passport.authenticate('login', {session: false}), cardCtrl.getAll); If I transform like you said, this code gets broken, because getAll is not more a property with function.
0

Working DEMO

You're defining getAll as a member property but you need to define it as a normal member method

Typescript overriding features works properly with member methods and not properties.

abstract class BaseCtrl {
    abstract model;    
    // Get all
    getAll (req, res) {
        this.model.find({}, (err, docs) => {
            if (err) { return console.error(err); }
            res.json(docs);
        });
    };
}

export class CardCtrl extends BaseCtrl {   
  getAll (req, res) {
    super.getAll(req, res);
  }

}

Propably, you may need to use getAll as a reference when passing to the router,So you may need to bind the scope like this cardCtrl.getAll.bind(cardCtrl);

3 Comments

Hi Mouneer. Have you ever faced the problem that "this" is undefined in the base class, using this code? I'm getting this error and I don't know why!
check my edit. Instead of using it as cardCtrl.getAll bind the scope. Got it?
Great! Thank you so much Mouneer! :)

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.