Skip to content

Cannot use class before definition #10675

Closed
@letmaik

Description

@letmaik

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions