TSM
TSM

Reputation: 189

Typescript: How to access super. inside of callback?

I try to access a method from the extended class inside of an Callback:

Model.findOne( { _id: id }, function( err, rec ){
    super.handleFind( err, rec ); 
});

When I compile my Typescript I see following error:

error TS2660: 'super' can only be referenced in members of derived classes or object literal expressions.

When I then run the JavaScript, I get:

TypeError: Cannot read property 'call' of undefined

If - before the Callback - I do something like let fct = super.handleFind; it seems to work, but this is undefined inside of handleFind() - and I need the this context.

Upvotes: 1

Views: 1420

Answers (2)

guest271314
guest271314

Reputation: 1

You can use Function.prototype.call() to call the anonymous function passed to .findOne() with context set to this : Model class

class Test {
  constructor() {}
  handleFind(err, rec) {
    console.log(err, rec)
  }
}

class Model extends Test {
  constructor() {
    super()
  }
  findOne(id, fn) {
    fn.call(this, id, "err")
  }
}

var model = new Model();

model.findOne({id: 123}, function(err, rec) {
  this.handleFind(err, rec)
});

Upvotes: -1

Trash Can
Trash Can

Reputation: 6814

Assume handleFile is defined in the parent class, it will then be inherited by your subclass, unless you are overriding handleFile in your subclass and you want to use the implementation of handleFile from the superclass instead, then you can just call it using this.handleFile.

The second issue is that you are passing a function() {...} callback to Model.findOne, if you want to preserve the this context (make it point to the current instance of your subclass), use arrow function instead, so change your function to this

 // Use arrow function to make 'this' point to the current instance of the
 // enclosing class
Model.findOne( { _id: id }, ( err, rec ) => {
    super.handleFind( err, rec ); 
});

Upvotes: 2

Related Questions