I am currently working on developing a versatile function that can retrieve configuration settings based on an enum input.
Within my modules, I aim to implement a method called getConfiguration
that will provide me with all the necessary environment variables.
For instance:
enum PackageAEnvs {
API_KEY = "API_KEY"
}
enum PackageBEnvs {
ADMIN_URL = "ADMIN_URL"
}
My ideal setup would look something like this:
const getConfiguration = <T extends string[]> (conf: T): Record<T, string>{
return conf.reduce( (acc, val) => {
const env = process.env[val];
if(! env) throw new Error()
return { ...acc, [val]: env}
}, {})
}
In this case, TypeScript should flag any errors if a key is missing:
const { randomKey} = getConfiguration<PackageAEnvs>() <-- TypeScript error expected
One approach I discovered involves using a specific type:
type Conf = "K1" | "K2"
type Config = {[Property in Conf]: string}
const getConfig = (): Config => {
return {
K1: "2",
K2: "2"
}
}
const { someKey } = getConf() // <-- error
However, I'm attempting to figure out how to make the getConfig function generic enough to accommodate any type. Is this feasible?