microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.17k stars 12.38k forks source link

`tsc` with `--target ESNext` fails but the same configuration succeeds on the playground. #45297

Open scharf opened 3 years ago

scharf commented 3 years ago

Bug Report

tsc causes errors for --target ESNext for some order of initialized variables and variables initialized in the constructor.

Why does the code produce errors for ESNext and no error for any other target?

πŸ”Ž Search Terms

πŸ•— Version & Regression Information

The command line fails on the code where the playground succeeds.

⏯ Playground Link

You have to set the --target to ESNext for this script Playground link with relevant code

πŸ’» Code

Compiling this code with

./node_modules/.bin/tsc --target ESNext x.ts

function writeVal(a: number, b: any): number {
    console.log(β€˜writeVal’, a, b);
    return a;
}
class TestClass {
    a: number;
    public b = writeVal(2, this.z);    
    constructor(public z: number) {
        this.a = writeVal(1, this.z);
    }
    public c = writeVal(3, this.z);
}

I get the following error:

x.ts:7:33 - error TS2729: Property β€˜z’ is used before its initialization.

7     public b = writeVal(2, this.z);
                                  ~

  x.ts:8:17
    8     constructor(public z: number) {
                      ~~~~~~~~~~~~~~~~
    β€˜z’ is declared here.

x.ts:11:33 - error TS2729: Property β€˜z’ is used before its initialization.

11     public c = writeVal(3, this.z);
                                   ~

  x.ts:8:17
    8     constructor(public z: number) {
                      ~~~~~~~~~~~~~~~~
    β€˜z’ is declared here.

Found 2 errors.

πŸ™ Actual behavior

Running the code above in the playground there is no error, but tsc throws errors and fails to compile.

πŸ™‚ Expected behavior

Playground and the compiler should produce the same errors.

scharf commented 3 years ago

This is the las version where the code compiles successfully:

npm i typescript@4.3.0-dev.20210407

This is the first version when the code breaks:

npm i typescript@4.3.0-dev.20210408

scharf commented 3 years ago

It is broken up to version npm i typescript@4.4.0-dev.20210802

MartinJohns commented 3 years ago

I get the same error in the playground: https://www.typescriptlang.org/play?useDefineForClassFields=true&target=99&ts=4.4.0-beta#code/GYVwdgxgLglg9mABAdwE4ygUwGoEMA2AFLgFyJggC2ARpqgDSLVm5gCeAlGRTXYgN4AoRCMQQEAZzj5MAOnxwA5oQDkaDDgIrGuRtQ4BuYaNSYoIVElxGAvoIj5cEiYgAqmCVADCj5wOMipORUtKhGoogADiDU+DAQTIgAvCjoWHhEAEyMUAAWMBKyAF6GEQFiklCoINBwqITRsfGIRdwhdBz+ERF5BbK4yakaGYQAjDn5hSXhonYRjXEJCSnq6QSEAMwTfdOCNkA

Note that useDefineForClassFields is by default true when targeting ESNext, but it needs to separately enabled in the Playground.