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

Improve error message when calling a class as a function #8948

Open
JonnyBurger opened this Issue Oct 31, 2018 · 1 comment

Comments

Projects
None yet
2 participants
@JonnyBurger

JonnyBurger commented Oct 31, 2018

Feature Request

Is your feature request related to a problem? Please describe.
In new versions of Chrome and Node, there is a good error message for when you call a class as a function. My proposal would be to add a more user-friendly message in the next major version of Babel.

Consider the following code:

class A {}
A()

In Chrome and Node.js, this results in the following error:

Uncaught TypeError: Class constructor A cannot be invoked without 'new'

In transpiled Babel code, the error is instead:

Cannot call a class as a function

It would be an improvement to the developer-friendliness if the error message is close the one in V8.

Describe the solution you'd like

The above code compiles to:

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var A = function A() {
  _classCallCheck(this, A);
};

A();

My desired output would be:

'use strict';

function _classCallCheck(instance, Constructor) {
	if (!(instance instanceof Constructor)) {
		throw new TypeError(
			'Class constructor ' +
				Constructor.name +
				" cannot be invoked without 'new'"
		);
	}
}

let A = function A() {
	_classCallCheck(this, A);
};

A();

This would align the error message with Chrome and Node.js.

Describe alternatives you've considered
N/A

Teachability, Documentation, Adoption, Migration Strategy
Since users might check the error message using try / catch, I would recommend to only make this change in the next major version of Babel.

I am happy to implement this if the community agrees.

Thanks for considering!

@babel-bot

This comment has been minimized.

Collaborator

babel-bot commented Oct 31, 2018

Hey @JonnyBurger! We really appreciate you taking the time to report an issue. The collaborators
on this project attempt to help as many people as possible, but we're a limited number of volunteers,
so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack
community that typically always has someone willing to help. You can sign-up here
for an invite.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment