Given I allow the user to supply an object of type,
type EnvironmentVars = { [keys: string]: any;}
How can I dynamically access the type of the value at a certain key when I don't know what the object looks like up front? The object is defined by the user and can be any key value pair. I am able to retrieve the correct value (envVars[key]
comes back correct), but its type is always any
. Here is the function to retrieve the value at a given key:
const getEnvVarAtKey<T>(key: keyof T) { const envVars = getAllEnvVars(); // This could be any object of key/value pairs supplied by the user return envVars[key]; // I need this to be typed properly!!!}
I think the crux of my problem is that I cant dynamically access the T[key]
since I don't know what the keys are in advance.
Expected behavior:
If the user sets the env vars to be
const envVars = { colorScheme: 'dark', authenticated: false, someKey: 'someVal' }
Then the following vars should be typed accordingly.
// This should return 'dark' and be of type stringconst colorScheme = getEnvVarAtKey<typeof envVars>('colorScheme'); // This should return false and be of type booleanconst authenticated = getEnvVarAtKey<typeof envVars>('authenticated');
Actual behavior:
// This returns 'dark' but is type anyconst colorScheme = getEnvVarAtKey<typeof envVars>('colorScheme'); // This returns false but is type anyconst authenticated = getEnvVarAtKey<typeof envVars>('authenticated');