Skip to content

Commit

Permalink
Derived constructors should not be allowed to return primitives (#13571)
Browse files Browse the repository at this point in the history
Closes gh-13571
  • Loading branch information
dhrubesh authored and nicolo-ribaudo committed Aug 9, 2021
1 parent ab79f08 commit 23d4f8c
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 3 deletions.
3 changes: 3 additions & 0 deletions packages/babel-helpers/src/helpers.js
Expand Up @@ -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);
}
`;
Expand Down
@@ -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");
@@ -0,0 +1,6 @@
class Foo extends Bar {
constructor() {
super();
return 3;
}
}
@@ -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);
Expand Up @@ -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");

0 comments on commit 23d4f8c

Please sign in to comment.