Derived constructors should not be allowed to return primitives (#13571)

Closes gh-13571
This commit is contained in:
dhrubesh 2021-07-19 17:15:01 +05:30 committed by Nicolò Ribaudo
parent ab79f08b63
commit 23d4f8c563
5 changed files with 47 additions and 3 deletions

View File

@ -617,7 +617,10 @@ helpers.possibleConstructorReturn = helper("7.0.0-beta.0")`
export default function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return assertThisInitialized(self);
}
`;

View File

@ -0,0 +1,18 @@
class Bar {}
class Foo extends Bar {
constructor() {
super();
return 3;
}
}
class Foo2 extends Bar {
constructor() {
super();
return null;
}
}
expect(() => new Foo()).toThrow("Derived constructors may only return object or undefined");
expect(() => new Foo2()).toThrow("Derived constructors may only return object or undefined");

View File

@ -0,0 +1,6 @@
class Foo extends Bar {
constructor() {
super();
return 3;
}
}

View File

@ -0,0 +1,17 @@
var Foo = /*#__PURE__*/function (_Bar) {
"use strict";
babelHelpers.inherits(Foo, _Bar);
var _super = babelHelpers.createSuper(Foo);
function Foo() {
var _this;
babelHelpers.classCallCheck(this, Foo);
_this = _super.call(this);
return babelHelpers.possibleConstructorReturn(_this, 3);
}
return Foo;
}(Bar);

View File

@ -43,16 +43,16 @@ expect(instance).toBe(singleton);
instance = new Sub;
expect(instance).toBe(singleton);
class Null extends Foo {
class Undefined extends Foo {
constructor() {
if (false) {
super();
}
return null;
return;
super();
}
}
expect(() => {
new Null();
new Undefined();
}).toThrow("this");