0

When I define a decorator in TypeScript in the format:

function Log2(target: any, name: string, descriptor: PropertyDescriptor) {
…
   console.log(descriptor);
…
} 

the descriptor is showing null. I use VS Code and the target in tsconfig.json is "target": "ES2016". I also enabled "experimentalDecorators": true.

My VS Code edition is 1.70.2 and TypeScript version is 4.7.3.

What am I doing wrong here? Why is descriptor always coming null?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

The code in app.ts is just simple function like as follows

function Log(target: any, propertyName: string | Symbol) {
  console.log("Property decorator!");
  console.log(target, propertyName);
}

function Log2(target: any, name: string, descriptor: PropertyDescriptor) {
  console.log("Accessor decorator!");
  console.log(target);
  console.log(name);
  console.log(descriptor);
}

function Log3(
  target: any,
  name: string | Symbol,
  descriptor: PropertyDescriptor
) {
  console.log("Method decorator!");
  console.log(target);
  console.log(name);
  console.log(descriptor);
}

function Log4(target: any, name: string | Symbol, position: number) {
  console.log("Parameter decorator!");
  console.log(target);
  console.log(name);
  console.log(position);
}

class Product {
  @Log
  title: string;
  private _price: number;

  @Log2
  set price(val: number) {
    if (val > 0) {
      this._price = val;
    } else {
      throw new Error("Invalid price - should be positive!");
    }
  }

  constructor(t: string, p: number) {
    this.title = t;
    this._price = p;
  }

  @Log3
  getPriceWithTax(@Log4 tax: number) {
    return this._price * (1 + tax);
  }
}

The issue is resolved when i tried like menioned in this post by specifying the target and the null is gone and getting proper details.

tsc -t es5 -w app https://stackoverflow.com/a/44285244/18735323

from the console window Details from console window