TypeScript: How to Handle Dynamic Keys in an Object with Specific Value Types
I'm upgrading from an older version and I've tried everything I can think of but Could someone explain I've looked through the documentation and I'm still confused about I'm working on a project where I need to define an object with dynamic keys, but each key must have a specific value type... For instance, I want to create an object where keys are strings and values can either be a number or an array of strings. I've tried to use an index signature, but I keep running into issues when trying to access the values, especially when TypeScript need to infer the type correctly. Hereβs what Iβve attempted: ```typescript type ValueType = number | string[]; interface MyObject { [key: string]: ValueType; } const myData: MyObject = { key1: 42, key2: ["value1", "value2"], }; const logData = (key: string) => { const value = myData[key]; console.log(value); }; logData('key1'); // Should log: 42 logData('key2'); // Should log: ["value1", "value2"] ``` However, I noticed that when I try to do something like this: ```typescript const newValue: number = myData['key2']; // behavior: Type 'string[]' is not assignable to type 'number' ``` This results in an behavior because TypeScript isn't narrowing down the type. How can I ensure that I can safely access these values without TypeScript throwing an behavior? Is there a better way to type this structure or a specific way to enforce value types while accessing the dynamic keys? I'm using TypeScript version 4.5.2 and this behavior is driving me a bit crazy. Any advice would be appreciated! How would you solve this? Thanks for taking the time to read this!