One could argue that the behavior in TypeScript could be considered a bug, although perhaps not a critical one.
The issue arises because when Object
is called, it ignores the context of this
and instead returns a new empty object. In the case of TypeScript compiling code for ES5 environments, it results in the following call within the Example
function:
function Example() {
return Object.call(this) || this;
}
The result of Object.call(this)
is essentially equivalent to creating an empty object with {}
.
To work around this issue, it's advisable to avoid such constructs.
The challenge lies in the fact that the code is generated by a customized JSweet version, where only certain parts are transpiled. Classes that should not be transpiled are simply mapped to Object due to limitations in removing the extends clause without significant modifications to JSweet.
If targeting ES2015+ environment eliminates the problem since it specifically pertains to TypeScript output for ES5 and earlier versions. Alternatively, submitting an issue on the TypeScript issues list or contributing a fix via a pull request may be necessary if unable to upgrade. Unlike extending other built-in objects like Error
or Array
, resolving this issue is straightforward: ignoring the extends clause altogether.
Another approach, as mentioned in a comment, could involve creating a trivial class that does nothing:
class FauxObject { }
Using this class instead of Object
(e.g., class Example extends FauxObject
) can serve as a workaround.
For reference, the complete compiled version showcases the section marking the call to Object
with ******
:
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Example = /** @class */ (function (_super) {
__extends(Example, _super);
function Example() {
return _super.call(this) || this; // ******
}
Example.prototype.getHello = function () {
return "Hello";
};
return Example;
}(Object));
var greeter = new Example();
alert(greeter.getHello());
In your scenario, _super
represents Object
.