Skip to content

Cannot use class before definition #10675

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

Closed
letmaik opened this issue Sep 1, 2016 · 3 comments
Closed

Cannot use class before definition #10675

letmaik opened this issue Sep 1, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@letmaik
Copy link
Member

letmaik commented Sep 1, 2016

TypeScript Version: 2.0

Code

new A()
class A {}

Expected behavior:
The code should run without error.
EDIT: The code is invalid, see below. Expected behavior is a compile-time error.

Actual behavior:
The first line throws a "TypeError: A is not a constructor".
This is because class A {} is transpiled to var A = ... and kept in the same code order. If A was transpiled as function A () {...} then it would work as function statements are hoisted but function expressions are not.

Babel and traceur do the same thing, so maybe this is just a hard issue and not worth solving as eventually there will be native class support anyway in engines.

The problem becomes more obscure when doing things like:

class B extends A {}
class A {}

Same issue but the error changes to a weird TypeError: b is undefined.

I think either this should be solved or alternatively a compile-time error thrown if the target is <ES2015.

EDIT: As detailed in #5207 class declarations are actually not hoistable (see ES2015 spec), so the only problem here is that there is no compile-time error and the code above is actually invalid ES2015 code.

@kitsonk
Copy link
Contributor

kitsonk commented Sep 1, 2016

Duplicate of #5207

@mhegazy mhegazy added the Duplicate An existing issue was already created label Sep 1, 2016
@mhegazy mhegazy closed this as completed Sep 1, 2016
@letmaik
Copy link
Member Author

letmaik commented Sep 2, 2016

Thanks, I didn't see that. I edited the issue text as I was clearly wrong in assuming that class declarations are hoistable where in fact they are not.

@kitsonk
Copy link
Contributor

kitsonk commented Sep 2, 2016

Yeah, it was a hard one to find, but I remembered it being brought up before (and I thought I had remembered about them not being hoistable too)

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants