Created
August 13, 2019 09:41
-
-
Save vajahath/8ebcff0f1334d81e694eb7ee6826dc85 to your computer and use it in GitHub Desktop.
typescript decorator example
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
// function decorator example | |
function keepTrack() { | |
// stores(or tracks) input and output | |
const track: [any, any][] = []; | |
return { | |
tracker: <MethodDecorator>( | |
function(target, prop, descriptor: PropertyDescriptor) { | |
const method = descriptor.value; | |
descriptor.value = function(...args: any[]) { | |
const result = method.apply(this, args); | |
track.push([args, result]); | |
return result; | |
}; | |
} | |
), | |
logger: <() => void>function() { | |
return track; | |
} | |
}; | |
} | |
const { tracker, logger } = keepTrack(); | |
class Cool { | |
@tracker | |
static add(a: number, b: number) { | |
return a + b; | |
} | |
@tracker | |
static makeString(a: string, b: string, c: string) { | |
return `~~~${a + b + c}~~~`; | |
} | |
} | |
// calls | |
console.log(Cool.add(5, 8)); | |
console.log(Cool.makeString("lollipop/", "stuffs/", "everywhere")); | |
console.log("---------------logger-----------------\n", logger()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment