Search code examples
typescriptecmascript-6es6-classtypescript-decoratortypescript-class

Extending type when extending an ES6 class with a TypeScript decorator


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 ?


Solution

  • 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.