Last active
April 29, 2024 22:35
-
-
Save jotafeldmann/c3129225ba5d0c26b5fb32273752e8fc to your computer and use it in GitHub Desktop.
typescript-method-decorator.ts
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
// Edit on https://gist.github.com/jotafeldmann/c3129225ba5d0c26b5fb32273752e8fc | |
// Test on https://replit.com/@jotafeldmann/typescript-method-decorator#index.ts | |
// "experimentalDecorators": true | |
function log(target: any, propertyName: string, descriptor: PropertyDescriptor) { | |
const originalMethod = descriptor.value; | |
descriptor.value = function (...args: any[]) { | |
const result = originalMethod.apply(this, args); | |
console.log(`${propertyName}(${args}) = ${result}`); | |
return result; | |
}; | |
return descriptor; | |
} | |
// Usage: | |
class AnyClass { | |
@log | |
private privateMethod(arg: string): boolean { | |
return arg === "1"; | |
} | |
@log | |
public publicMethod(arg: string): boolean { | |
return this.privateMethod(arg); | |
} | |
} | |
const anyClass = new AnyClass(); | |
anyClass.publicMethod("2"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment