Skip to content

Instantly share code, notes, and snippets.

@countnazgul
Last active April 17, 2022 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save countnazgul/240bcb813a12dc349ffd2a00e104976b to your computer and use it in GitHub Desktop.
Save countnazgul/240bcb813a12dc349ffd2a00e104976b to your computer and use it in GitHub Desktop.
[Method decorator] Example how to create method decorator #typescript
// Define the decorator
// if the method parameter is not passed
// then the decorator will return the result of someOtherFunction()
// as value for the parameter
export const decoratorFunction = (index: number) => (
target: any,
key: string,
propDesc: PropertyDescriptor
) => {
let originalFunction: Function = propDesc.value;
propDesc.value = function () {
let argValue = arguments[index];
let newArgs = [];
for (let i = 0; i < arguments.length; i++) newArgs.push(arguments[i]);
newArgs[index] = argValue || someOtherFunction();
return originalFunction.apply(this, newArgs);
};
return propDesc;
};
function someOtherFunction(): string {
return "some value"
}
//---------------------
class MyClas {
constructor() {}
@decoratorFunction(1) // the number is the required param index to be checked
MyMethod(param1: string, param2?: string) {
// if param2 is not provided the decorator will
// "replace" it with the result of someOtherFunction()
}
@decoratorFunction(0) // the number is the required param index to be checked
MyOtherMethod(param1?: string) {
// if param1 is not provided the decorator will
// "replace" it with the result of someOtherFunction()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment