Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

ecmascript 6 - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...