CodexBloom - Programming Q&A Platform

How can I implement a TypeScript class that supports dynamic method binding with overloads?

👀 Views: 37 💬 Answers: 1 📅 Created: 2025-09-07
TypeScript classes overloading design-patterns

This might be a silly question, but I'm performance testing and After trying multiple solutions online, I still can't figure this out... I'm sure I'm missing something obvious here, but Currently developing a feature in a TypeScript-based open-source library where I need to allow for dynamic method binding while also supporting method overloads... The core idea is to create a class that can register multiple implementations of a method with varying parameters and invoke the appropriate one based on the arguments passed at runtime. Here's a simplified version of what I have so far: ```typescript class DynamicBinder { private methods: { [key: string]: Function[] } = {}; public register(methodName: string, fn: Function): void { if (!this.methods[methodName]) { this.methods[methodName] = []; } this.methods[methodName].push(fn); } public invoke(methodName: string, ...args: any[]): any { const fns = this.methods[methodName]; if (fns) { for (const fn of fns) { // Here I'm trying to dynamically bind based on the number of arguments if (fn.length === args.length) { return fn(...args); } } } throw new Error(`No method found for ${methodName} with ${args.length} arguments.`); } } ``` What I find is that while the registration works as expected, the invocation logic doesn't seem robust enough to handle more complex scenarios. If I register methods like this: ```typescript const binder = new DynamicBinder(); binder.register('calculate', (x: number) => x * 2); binder.register('calculate', (x: number, y: number) => x + y); ``` When I try to call `binder.invoke('calculate', 5);`, it returns 10 as expected. However, for `binder.invoke('calculate', 5, 10);`, it seems to skip the correct overload, or sometimes throws an error even when a valid overload exists. I need a way to ensure that the correct function gets called based on the exact argument list. I’ve explored various approaches, including using TypeScript's function overloads directly in the class, but that seems to complicate the registration process. I want to ensure that my solution remains simple and maintainable, especially as the library grows and more methods are added. Any suggestions on best practices for handling dynamic method binding with overloads in TypeScript? Should I consider a different design pattern, or is there a simpler way to achieve this functionality? Looking forward to any insights or examples that might help clarify this! This is part of a larger service I'm building. How would you solve this? Any suggestions would be helpful. I'm working on a REST API that needs to handle this.