Skip to content

Instantly share code, notes, and snippets.

@cododel
Created October 14, 2024 20:45
Show Gist options
  • Save cododel/b5fd895cd7d89198cb307be9433450c3 to your computer and use it in GitHub Desktop.
Save cododel/b5fd895cd7d89198cb307be9433450c3 to your computer and use it in GitHub Desktop.
Helper to make class instance callable
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];
}
});
}
@cododel
Copy link
Author

cododel commented Oct 30, 2024

Subscribe to my telegram channel, don’t miss new interesting solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment