Extending type when extending an ES6 class with a TypeScript decorator

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 05:22:47

问题


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:

@decorator
class Person{

}

and this is the decorator:

const decorator = (target)=>{
    return class New_Class extends target {
        myProp:string
    }
}

but myProp is not a known property of Person:

person.myProp //Error - myProp does not exist on type Person

How can I decorate a typescript class and preserve type completion, type safety, etc ?


回答1:


To supplement jcalz response, going back to the definition of the Decorator Pattern, it does not change the interface/contracts of its target. It's not just terminology. TypeScript decorators share similarities with Java annotations and .NET attributes which are aligned with the fact not to change the interface: they just add metadata.

Class mixin is a good candidate to solve your question. But it's better not to use "decorator" in its name in order to avoid confusion.




回答2:


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!




回答3:


I found a solution to implement kind-of multiple heritage (really cascades it) but it's worth taking a look.

Supose you have a class Base with a few properties and methods:

class Base {
    tableName = 'My table name';
    hello(name) {
     return `hello ${name}`;
    }
}

And you want a class to extend Base but you also have defined some properties you want to reuse. For that will do the following function:

type Constructor<T = {}> = new (...args: any[]) => T;
function UserFields<TBase extends Constructor>(Base: TBase) {
    return class extends Base {
        name: string;
        email: string;
    };
}

Now we can do a class that extends Base and extends UserFields and typescript language service will find properties from both classes. It emulates a multiple heritage but it's really a cascade.

class User extends UserFields(Base) { }
const u = new User();
u.tableName = 'users'; // ok
u.name = 'John'; // ok

By this way you could reuse the UserFields function with any other classes. A clear example of that is if you want to expose the User object on client side as a "clean" object and have the fields available and then you have a UserDb object with connections to database and any other server side methods can have the same fields too. We only define the database fields once!

Another good thing is you could chain mixins mixin1(mixin2....(Base)) to have as many attributes as you want to have in the same class.

Everybody is expecting the decorator attributes to be visible by typescript, but meanwhile is a good solution.



来源:https://stackoverflow.com/questions/54892401/extending-type-when-extending-an-es6-class-with-a-typescript-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!