-
Notifications
You must be signed in to change notification settings - Fork 12.8k
In target: ES5, Base class constructor's primitive return value should be ignored #51738
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@MartinJohns The change can be trivially done in the downlevelingβit requires no type information. new /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
- var _this = _super.call(this) || this;
+ var _this = _super.call(this);
+ if (_this === null || (typeof _this !== "object" && typeof _this !== "function"))
+ _this = this;
console.log(typeof _this);
return _this;
}
return class_1;
}(/** @class */ (function () {
function class_2() {
return 1;
}
return class_2;
}()))); FWIW, anything that Babel does right but tsc does wrong looks like a bug to me. |
Nevermind my earlier comment. I wrongly assumed the JavaScript will behave the same. |
You probably should have specified that this only happens with ES5-downleveled code. From the OP it seemed like you meant this happened regardless of |
You should use Babel in that case. The TS emit takes some complexity/compliance tradeoffs and is much less configurable. I don't think we want to risk breaking any ES5 programs at this point given how old of a target it is. |
I can guess the historical context here (tsc implementing classes before the latter getting standardized), but IMO the current behavior doesn't benefit anyone and is unlikely to be relied on. If function SomethingThatReturnsEitherObjectOrNumberIDK() {
if (somethingNotGoingWell) return 1;
return {
the: "actual object that I want to construct",
};
}
declare class SomethingThatReturnsEitherObjectOrNumberIDK {
the?: string;
}
new class extends SomethingThatReturnsEitherObjectOrNumberIDK {
constructor() {
super();
if (typeof this === "number")
return { the: `number wrapped into an object: ${this}` }; // type: { the: never }
}
} But that doesn't even get correct types! Why would someone use tsc, choose its bizarre subclassing behavior, but also disregard the types? Built-in subclassing not working is a missed but understandable tradeoff, but this one seems niche and not as breaking-change-prone, while increasing tsc's conformance. |
Bug Report
π Search Terms
class, extends, constructor, return primitive
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Logs "number"
π Expected behavior
Logs "object"
The text was updated successfully, but these errors were encountered: