Skip to content

Sub-classes with field initializers crash if constructor does not start with super() #33895

@robpalme

Description

@robpalme

TypeScript Version: 3.7.0-beta

Search Terms: public class fields

Code:

class Base {}
class Sub extends Base {
    // @ts-ignore
    constructor() {
        console.log('hi');
        super();
    }
    field = 0;
}
new Sub();

Expected behavior:

The input code is valid (future) JS that does not throw. So the emitted code should equally not throw.

Actual behavior:

The emitted code throws ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor.

The reason is that if a sub-class has field initializers, TypeScript currently requires the first line of the constructor to be super(). This is a restriction of TypeScript, not of JavaScript. If you violate this rule, the emitted code crashes.

Emitted code:

class Base {}
class Sub extends Base {
    // @ts-ignore
    constructor() {
        this.field = 0;
        console.log('hi');
        super();
    }
}
new Sub();

Playground Link: Playground repro

Related Issues: Issue 33751 was marked as a duplicate and auto-closed. I think this missed my comment so opening this as an independent issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDuplicateAn existing issue was already createdEffort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do thisNeeds ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions