Extending type when extending an ES6 class with a TypeScript decorator

前端 未结 3 1664
栀梦
栀梦 2021-01-12 11:34

I am trying to decorate a class with a decorator (a-la-angular style), and add methods and properties to it.

this is my example decorated class:

         


        
3条回答
  •  我在风中等你
    2021-01-12 11:49

    There's a GitHub issue about this with lots of discussion. I think the summary of it is: decorators do not mutate the type of a class (most of the discussion is about whether it should or shouldn't be that way) and therefore you can't do it the way you want, like this:

    const decorator = (target: new (...args: any) => any) => {
      // note I'm extending target, not Person, otherwise you're not
      // decorating the passed-in thing
      return class New_Class extends target {
        myProp!: string
      }
    }
    
    @decorator
    class Person {
      noKnowledgeOfMyProp: this['myProp'] = "oops"; // error
    }
    
    declare const p: Person;
    p.myProp; // error, uh oh
    

    What you could do instead is just use your decorator as a plain mixin function, and have Person extend the return value of that. You end up having two class definitions... one which is passed into decorator and one which your new class extends. The "inner" class (passed to decorator()) still has no knowledge of the added props, but the "outer" class does:

    class Person extends decorator(class {
      innerProp: string = "inner";
      noKnowledgeOfMyProp: this['myProp'] = "oops"; // error
    }) {
      outerProp: string = "outer"
      hasKnowledgeOrMyProp: this['myProp'] = "okay"; // okay
    }
    
    declare const p: Person;
    p.myProp; // okay
    

    Does that help? Good luck!

提交回复
热议问题