Decorator Composition
Multiple decorators can be applied to a declaration, as in the following examples:
-
On a single line:
1@f @g x
-
On multiple lines:
123@f
@g
x
When multiple decorators apply to a single declaration, their evaluation is similar to function composition in mathematics. In this model, when composing functions f and g, the resulting composite (f ∘ g)(x) is equivalent to f(g(x)).
As such, the following steps are performed when evaluating multiple decorators on a single declaration in TypeScript:
- The expressions for each decorator are evaluated top-to-bottom.
- The results are then called as functions from bottom-to-top.
If we were to use decorator factories, we can observe this evaluation order with the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function f() { console.log( "f(): evaluated" ); return function (target, propertyKey: string, descriptor: PropertyDescriptor) { console.log( "f(): called" ); } } function g() { console.log( "g(): evaluated" ); return function (target, propertyKey: string, descriptor: PropertyDescriptor) { console.log( "g(): called" ); } } class C { @f() @g() method() {} } |
Which would print this output to the console:
1 2 3 4 | f(): evaluated g(): evaluated g(): called f(): called |
Please login to continue.