typescripttypescript-decorator

TypeScript playground and TSX give different method decorator outputs


Consider the following code:

function decorate(target: any, context: any) {
    console.log("Method details:", {target, context});
}

class Example {
    @decorate
    public helloWorld() {
    }
}

When I run this in the TypeScript Playground, I get the following result:

[LOG]: "Method details:",  {
  "target": {},
  "context": "helloWorld"
}

However, when I run this with npx tsx example.ts, I get a different result:

Method details: {
  target: [Function: helloWorld],
  context: {
    kind: 'method',
    name: 'helloWorld',
    metadata: [Object: null prototype] {},
    addInitializer: [Function: addInitializer],
    static: false,
    private: false,
    access: { has: [Function (anonymous)], get: [Function (anonymous)] }
  }
}

What causes these outputs to be different, and why?


Solution

  • There are two implementations of decorators. Which to use is governed by the experimentalDecorators compiler option.

    You can toggle this in the playground by clicking "TS Config" and finding experimentalDecorators.

    You probably want it disabled unless using a library that requires the experimental version of decorators, which are now considered "legacy" as of Typescript 5.0.