We're using TypeScript classes with inheritance and have run into an apparent scoping issue. TypeScript/JavaScript is not allowing us to call 'super' from within a promise structure (or even from an enclosed function). We're receiving this error:
TypeScript: 'super' Can Only Be Referenced in Members of Derived Classes or Object Literal Expressions
Is there a way around this? Here's the code:
export class VendorBill extends Transaction {
constructor() {
super();
}
save() {
let deferred = $.Deferred();
$.ajax({
type: "GET",
url: '/myrestapi',
success: function (data) {
deferred.resolve();
},
error: function (jqXHR: any, textStatus, errorThrown) {
deferred.reject()
}
})
$.when(deferred).always(function () {
super.save(); <----------- THIS IS CAUSING THE ERROR
})
}
}
We're using TypeScript classes with inheritance and have run into an apparent scoping issue. TypeScript/JavaScript is not allowing us to call 'super' from within a promise structure (or even from an enclosed function). We're receiving this error:
TypeScript: 'super' Can Only Be Referenced in Members of Derived Classes or Object Literal Expressions
Is there a way around this? Here's the code:
export class VendorBill extends Transaction {
constructor() {
super();
}
save() {
let deferred = $.Deferred();
$.ajax({
type: "GET",
url: '/myrestapi',
success: function (data) {
deferred.resolve();
},
error: function (jqXHR: any, textStatus, errorThrown) {
deferred.reject()
}
})
$.when(deferred).always(function () {
super.save(); <----------- THIS IS CAUSING THE ERROR
})
}
}
Share
Improve this question
asked Feb 10, 2017 at 22:22
A2MetalCoreA2MetalCore
1,6394 gold badges27 silver badges50 bronze badges
1
-
Also worth pointing out you're using the promise antipattern of using an extra deferred object when you don't need one. You can just do
$.ajax({...}).always(() => { super.save(); });
– Adam Jenkins Commented Feb 10, 2017 at 22:38
1 Answer
Reset to default 5The reason is that the piler turns super.save()
to:
_super.prototype.fn.call(this);
But this
isn't the right one because you're passing a function which isn't bound to the right context.
You can use an arrow function:
$.when(deferred).always(() => {
super.save();
})