Created
October 14, 2024 20:45
-
-
Save cododel/b5fd895cd7d89198cb307be9433450c3 to your computer and use it in GitHub Desktop.
Helper to make class instance callable
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
type hasCallMethod = { call: (...args: any[]) => any }; | |
export default function toCallable<T extends hasCallMethod>(instance: T) { | |
type argsType = Parameters<T["call"]> | |
const fn = (...args: argsType) => { | |
return instance.call(...args); | |
}; | |
return new Proxy(fn.bind(instance), { | |
apply: (target, _thisArg, argsList: argsType) => target(...argsList), | |
get: (target, prop) => { | |
// Delegate to the class instance if the property exists there | |
if (prop in instance) { | |
return instance[prop as keyof T]; | |
} | |
// Otherwise, look for it on the function | |
return target[prop as keyof typeof target]; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Subscribe to my telegram channel, don’t miss new interesting solutions