Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

annotations - Alias for decorator in typescript

I know there is alias for type:

type ShortTypeName = LooooooooooongTypeName

Now I am trying to simplify my complex typescript code with decorator, which I am not very familiar with. Supposed I have following code:

class Foo {
    @SomeDecorator(someConst1, someConst2, someConst3, someConst4)
    property1: string
    @SomeDecorator(someConst1, someConst2, someConst3, someConst4)
    property2: number
    @SomeDecorator(someConst1, someConst2, someConst3, someConst4)
    property3: Date
    @SomeDecorator(someConst1, someConst2, someConst3, someConst4)
    property4: Bar
}

I would like to use "alias" so that I can write it like:

alias D = SomeDecorator(someConst1, someConst2, someConst3, someConst4)

class Foo {
    @D
    property1: string
    @D
    property2: number
    @D
    property3: Date
    @D
    property4: Bar
}

I know that such alias does not exist, but I guess that this simplification can be done by declaring new decorator (i.e. declaring new function) D which calls SomeDecorator. How should I do it?


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

1 Reply

0 votes
by (71.8m points)

Ok I have found the solution. I can define D like the following code.

function D(target: any, propertyName: string) {
    const f = SomeDecoration(someConst1, someConst2, someConst3, someConst4)
    f(target, propertyName)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...