TypeScript 1.5 now has decorators.
Could someone provide a simple example demonstrating the proper way to implement a decorator and describe what the arguments in the possible valid decorator signatures mean?
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Additionally, are there any best practice considerations that should be kept in mind while implementing a decorator?
I ended up playing around with decorators and decided to document what I figured out for anyone who wants to take advantage of this before any documentation comes out. Please feel free to edit this if you see any mistakes.
A valid decorator should be:
- Assignable to one of the Decorator types (
ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator
).- Return a value (in the case of class decorators and method decorator) that is assignable to the decorated value.
Implementation parameters:
target
: The prototype of the class (Object
).propertyKey
: The name of the method (string
| symbol
).descriptor
: A TypedPropertyDescriptor
— If you're unfamiliar with a descriptor's keys, I would recommend reading about it in this documentation on Object.defineProperty
(it's the third parameter).Use:
class MyClass {
@log
myMethod(arg: string) {
return "Message -- " + arg;
}
}
Implementation:
function log(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
const originalMethod = descriptor.value; // save a reference to the original method
// NOTE: Do not use arrow syntax here. Use a function expression in
// order to use the correct value of `this` in this method (see notes below)
descriptor.value = function(...args: any[]) {
// pre
console.log("The method args are: " + JSON.stringify(args));
// run and store result
const result = originalMethod.apply(this, args);
// post
console.log("The return value is: " + result);
// return the result of the original method (or modify it before returning)
return result;
};
return descriptor;
}
Input:
new MyClass().myMethod("testing");
Output:
The method args are: ["testing"]
The return value is: Message -- testing
Notes:
this
will not be the instance's if you do.@enumerable(false)
and @log
at the same time (Example: Bad vs Good)TypedPropertyDescriptor
can be used to restrict what method signatures (Method Example) or accessor signatures (Accessor Example) the decorator can be put on.When using arguments, you must declare a function with the decorator's parameters then return a function with the signature of the example without arguments.
class MyClass {
@enumerable(false)
get prop() {
return true;
}
}
function enumerable(isEnumerable: boolean) {
return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
descriptor.enumerable = isEnumerable;
return descriptor;
};
}
Similar to a method decorator with some differences:
target
parameter is the constructor function itself and not the prototype.@isTestable
class MyClass {}
Implementation parameter:
target
: The class the decorator is declared on (TFunction extends Function
).Example use: Using the metadata api to store information on a class.
class MyClass {
@serialize
name: string;
}
Implementation parameters:
target
: The prototype of the class (Object
).propertyKey
: The name of the property (string
| symbol
).Example use: Creating a @serialize("serializedName")
decorator and adding the property name to a list of properties to serialize.
class MyClass {
myMethod(@myDecorator myParameter: string) {}
}
Implementation parameters:
target
: The prototype of the class (Function
—it seems Function
doesn't work anymore. You should use any
or Object
here now in order to use the decorator within any class. Or specify the class type(s) you want to restrict it to)propertyKey
: The name of the method (string
| symbol
).parameterIndex
: The index of parameter in the list of the function's parameters (number
).