Reputation: 1444
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?
Upvotes: 0
Views: 198
Reputation: 13489
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);
Upvotes: 0
Reputation: 26281
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);
}
}
Upvotes: 2