Last active
April 17, 2022 18:38
-
-
Save countnazgul/240bcb813a12dc349ffd2a00e104976b to your computer and use it in GitHub Desktop.
[Method decorator] Example how to create method decorator #typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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