Skip to content

Instantly share code, notes, and snippets.

@mrfzd
Created August 4, 2021 12:15
Show Gist options
  • Save mrfzd/872171d79f59242a677ff42351fedf6c to your computer and use it in GitHub Desktop.
Save mrfzd/872171d79f59242a677ff42351fedf6c to your computer and use it in GitHub Desktop.
TypeScript Decorators #101
// @experimentalDecorators
console.clear();
function computeFullName() {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
// target is the class name
// propertyKey is the method name in the class
// This is the method func itself
let originalMethod: Function = descriptor.value;
// console.log(originalMethod)
descriptor.value = function(args: Record<string, string>) {
args.fullName = `${args?.firstName || 'First Name'} ${args?.lastName || 'Last Name'}`;
// Here we would ideally want to return the func/method itself with the changes such as its args
return args;
}
return descriptor;
};
}
// Uncomment below to see it working in your console
/*
class ExampleClass {
@computeFullName()
someMethodName(params: Record<string, string>) {
const { fullName } = params;
return `Hello, ${params.fullName}`;
}
}
const testClass = new ExampleClass();
const myName = testClass.someMethodName({
firstName: 'John',
lastName: 'Smith',
});
console.log(myName)
*/
// Todo
// class someDummyClass {
// @mergeObjectArgs()
// whatIsYourName(params: Record<string, string>) {
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment