typescripttsconfigtsces2022

Why is typescript optional class property set to undefined for es2022


Typescript compiler handling of optional class properties seems to have changed from es2021 to es2022.

class A {
    a?: string
    b?: string
    constructor() {
        this.b = 'asd'
    }
}
console.log(new A())

with tsconfig target=es2021 results in

A: {
  "b": "asd"
} 

with tsconfig target=es2022 results in

A: {
  "a": undefined,
  "b": "asd"
} 

I cannot find any documentation regarding this change. Is this really intended behaviour and why?

It is easy to reproduce in ts playground by changing TS Config->Target


Solution

  • The difference is useDefineForClassFields :

    This flag is used as part of migrating to the upcoming standard version of class fields. TypeScript introduced class fields many years before it was ratified in TC39. The latest version of the upcoming specification has a different runtime behavior to TypeScript’s implementation but the same syntax.

    This flag switches to the upcoming ECMA runtime behavior.

    TS Documentation