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:
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!