CodexBloom - Programming Q&A Platform

TypeScript: How to Type a Function that Creates a Dictionary of Functions with Specific Signatures?

đź‘€ Views: 370 đź’¬ Answers: 1 đź“… Created: 2025-06-11
typescript type-inference function-signatures TypeScript

I'm upgrading from an older version and I'm upgrading from an older version and I'm stuck on something that should probably be simple... I'm working on a project and hit a roadblock. I'm trying to create a function in TypeScript that returns a dictionary (object) of functions. Each function in the dictionary should have a different signature based on an input parameter. I want to ensure that TypeScript correctly infers the types of the functions in the dictionary without running into type errors. Here’s what I've done so far: ```typescript type FunctionMap = { [key: string]: (arg: any) => any; }; function createFunctionDictionary(): FunctionMap { return { add: (x: number, y: number) => x + y, concat: (a: string, b: string) => a + b, }; } const functionDict = createFunctionDictionary(); const result1 = functionDict.add(1, 2); // Should be 3 const result2 = functionDict.concat('Hello, ', 'World!'); // Should be 'Hello, World!' ``` However, I’m working with type issues when I try to use these functions. TypeScript doesn’t seem to infer the specific types of each function correctly. For example, if I try to call `functionDict.add('1', '2')`, TypeScript allows it, even though it shouldn’t since `add` is supposed to take numbers. I’d like to know how I can refine the typing of the `FunctionMap` type so that TypeScript correctly checks the argument types based on the function name. I want to utilize TypeScript’s capabilities for strong typing, but I’m not sure how to structure this properly. Additionally, I’d appreciate any insights on best practices for handling dynamic functions like these in TypeScript. I'm currently using TypeScript version 4.5.2. Thanks! This is part of a larger service I'm building. Am I missing something obvious? I'm working on a service that needs to handle this. For context: I'm using Typescript on Windows 11. What am I doing wrong? I'm using Typescript latest in this project. I'm using Typescript LTS in this project. I'd be grateful for any help.