Microsoft/TypeScript

TS2401 does not work with `"target": "ESNext"`

Open

#54,445 建立於 2023年5月29日

在 GitHub 查看
 (5 留言) (3 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: classesHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

Bug Report

🔎 Search Terms

TS2401 ESNext return super

🕗 Version & Regression Information

  • This is the behavior in every version I tried (~4.9, ~5.0, ~5.1) (TS2401 seems to appear in 4.9)

⏯ Playground Link

Stackblitz link with relevant code (does not appear in Playground, appears in VSCode & Stackblitz ) Comment out "target": "ESNext" in tsconfig.json and the error will appear

💻 Code

class MyArray extends Array {
  constructor(public foo?: any) {
    return !foo ? [] : (super() as any);
    //                  ^^^^^^^
    // no error with `"target": "ESNext"`, otherwise:
    // A 'super' call must be a root-level statement within a constructor of a derived class that contains initialized properties, parameter properties, or private identifiers.(2401)
  }
}
new MyArray();

🙁 Actual behavior

No error when "target": "ESNext" The compiled code causes runtime error Must call super constructor in derived class before accessing 'this' or returning from derived constructor

🙂 Expected behavior

TS2401 when "target": "ESNext" OR runtime works fine, producing

class MyArray extends Array {
    foo;
    constructor(foo){
        var _temp;
        return !foo ? [] : (_temp = super(), this.foo = foo, _temp);
    }
}
new MyArray();

same as SWC does

Side note

SWC compiler can compile this just fine (as (_temp = super(), this.foo = foo, _temp)), so this code has runtime errors only when compiled with tsc.

貢獻者指南