3

I have a simple TypeScript tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "experimentalDecorators": true,
    ...

And a class that uses a decorator:

class MyClass {
    @myDecorator()
    myField: any;
}

The decorator causes myField to be emitted as a property that uses a __decorate function, the myDecorator function is passed to it.

After upgrading to the latest version (4.2.4) this stopped working in Visual Studio 2019, but it continues to work in VS Code (using 4.3.5) and continuous integration tools (in both 4.3.5 and older 3.* TypeScript releases).

After some investigation it appears that the emitted JavaScript has changed to include the fields explicitly, but only in the TypeScript 4.2.4 embedded in Visual Studio 2019. These explicit fields cause the __decorate to fail to create the new property with the same name.

Why has the emitted JS changed?

How do I fix it?

1 Answer 1

14

TL;DR: The fix for TypeScript property decorators breaking when you upgrade TypeScript is to add "useDefineForClassFields": false to your tsconfig.json.

This is due to a breaking change in TypeScript that was optional in 3.7, but appears to be the default in 4.2 (but not 4.3), and the way the embedded version of TypeScript in Visual Studio 2019 ignores settings.

Firstly we have a new flag: useDefineForClassFields - turning this on causes tsc to emit fields directly. This is expected to break decorators, but is apparently by design (even though it means useDefineForClassFields and experimentalDecorators now break each other).

As useDefineForClassFields is a breaking change it's supposed to default to false. However, to align with the ECMAScript standard it should default to true when target is ESNext or ES2020.

It doesn't. It defaults to false except in Visual Studio, where it defaults to true, regardless of your tsconfig.

3
  • Is that undocumented? The tsconfig.json docs link to the 3.7 release notes which do note "This can cause quite a bit of fallout for existing code...".
    – jonrsharpe
    Commented Aug 26, 2021 at 15:46
  • @jonrsharpe ah, I meant the decision to default it to true sometime after 3.7 and before 4.2 was undocumented. It was pretty clearly an experiment in 3.7, one I thought had failed given it breaks decorators (one of the main reasons to use TS rather than JS with ts-check for us). I'll clarify.
    – Keith
    Commented Aug 26, 2021 at 19:09
  • Thank you so much. Spent way too much time on this.
    – deojeff
    Commented Jul 1 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.