'How Typescript method decorator factory get target class type?

I want to print out whenever the listening properties change, and I want TS to prompt me for the properties of the target class instance:

type Property = {
  type?: any;
  value?: any;
  optionalTypes?: any[];
  observer?: (newVal: any, oldVal: any) => void;
};

function properties(prop: Property) {
  return function (target: any, name: string, desc?: any) {
    // impl
  };
}

class Index {
  @properties({
    type: Number,
    value: 0,
    observer(newVal) {
      // I hope this can access to target class;
      this.print(newVal);
    },
  })
  myProp;

  print(val) {
    console.log('New value: ', val);
  }
}

I have a solution to this problem, but it's very inelegant:

type Property = {
  type?: any;
  value?: any;
  optionalTypes?: any[];
  observer?: (newVal: any, oldVal: any) => void;
};

function properties<K>(prop: Property & ThisType<K>) {
  return function (target: K, name: string, desc?: any) {
    // impl
  };
}

class Index {
  // inelegant
  @properties<Index>({
    type: Number,
    value: 0,
    observer(newVal) {
      this.print(newVal);
    },
  })
  myProp;

  print(val) {
    console.log('New value: ', val);
  }
}

I need to pass the class instance type to the decorator, it is so inelegant.

Is there a better solution?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source