Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k 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 Answer

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...