tyepscript set type of 'this' on function decorator

93 Views Asked by At

I have a decorator that create a proxy over properties and whenever that property is changed to something new, it will let you do some side effect to happen

class A{
   @OnChange<number>(function(changes){
     console.log(typeof this); //the type of `this` here is `A` but eslint nag that it's any
     this.print()
   })
   n=0;
   
   print(){
      console.log(this.n);
   }
}

const a1= new A();
a1.n=2; // on calling this the `Print()` method will be called

playground: https://stackblitz.com/edit/typescript-ymasoh?file=index.ts

the eslint is whining about the type of this is any. I can't find any way to set the type of this in the decorator to current class.

so I am looking for a way that could set the type of this, something like :

function OnChange<T = any, U extend this>(callback: (this: U, simpleChange?: SimpleChange<T>) => void) {

as a surprise I expected that an arrow function would solve the issue, but unfortuantely in this case an arrow function make the situation worth and typescript find this as undefined

update

I created a bug for this in typescript repo https://github.com/microsoft/TypeScript/issues/47333 appreciate your like and thumbs up so ts team consider this as a bug

0

There are 0 best solutions below