简体   繁体   中英

Typescript inheritance

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?

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);
     }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM