Skip to content

Instantly share code, notes, and snippets.

@rphansen91
Last active April 1, 2022 23:04
Show Gist options
  • Save rphansen91/43775f5d5a48e6a43797905b023e6797 to your computer and use it in GitHub Desktop.
Save rphansen91/43775f5d5a48e6a43797905b023e6797 to your computer and use it in GitHub Desktop.
Generic Decorator
type Fn = (...args: any) => any
type Awaited<T> = T extends PromiseLike<infer U> ? U : T
export function someDecorator<V extends Fn>(method: V) {
// Do some initialization logic here
return async function (...args: Parameters<V>): Promise<Awaited<ReturnType<V>>> {
// Do some args manipulation or validation
const value = await method(...args)
// Do some value manipulation or validation
return value
}
}
async function someAsyncMethod(a: string, b: string) {
return { a, b }
}
const someDecoratedAsyncMethod = someDecorator(someAsyncMethod)
someDecoratedAsyncMethod('foo', 'bar')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment