CodexBloom - Programming Q&A Platform

TypeScript: implementing Dynamic Key Mapping in a Config Object

πŸ‘€ Views: 94 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
typescript react configuration TypeScript

I've been banging my head against this for hours. Quick question that's been bugging me - I'm working on a TypeScript project that involves dynamic configuration settings for a React application. I'm trying to create a configuration object where the keys are defined at runtime, and each key maps to a specific type depending on its value. However, I'm running into issues with TypeScript not recognizing the correct types for these dynamic keys. Here’s a simplified version of what I have so far: ```typescript type ConfigKey = 'apiUrl' | 'timeout' | 'retryAttempts'; interface ConfigValues { apiUrl: string; timeout: number; retryAttempts: number; } const config: Partial<Record<ConfigKey, ConfigValues[ConfigKey]>> = {}; const setConfig = <K extends ConfigKey>(key: K, value: ConfigValues[K]) => { config[key] = value; }; setConfig('apiUrl', 'https://api.example.com'); // Works fine setConfig('timeout', 5000); // Works fine setConfig('retryAttempts', 3); // Works fine setConfig('nonExistentKey', 'value'); // Type behavior here ``` The scenario arises when I try to call `setConfig` with a key that is not defined in the `ConfigKey` type. TypeScript correctly raises a type behavior for that, but I'm confused because I want to enforce that the config can only have values from the `ConfigKey`. After some troubleshooting, I also noticed that while TypeScript throws a type behavior for non-existent keys, if I use a variable instead of a literal string, TypeScript allows any string to pass through. For example: ```typescript const dynamicKey: ConfigKey = 'apiUrl'; // This is fine setConfig(dynamicKey, 'https://api.newexample.com'); // This works, but I expected a type behavior ``` How can I enforce stricter type checks so that `setConfig` only accepts valid keys at all times, including when using variables? I'm using TypeScript version 4.5.4. Any help would be appreciated! My development environment is Windows. How would you solve this? My team is using Typescript for this microservice. Could someone point me to the right documentation?