I am currently working on a project where I need to determine the type of property within a given Type:
type FooBarType {
foo: string,
bar: number
}
The function would be structured like this:
getType<K extends keyof T>(key: K): string
. Therefore, calling the function with foo
as the parameter should return string
:
getType<FooBarType>('foo' as as keyof FooBarType) // string
At this stage, I do not have a concrete implementation for the generic, so using indexed access types may not be applicable?
Do you think this is achievable?
Here's what I have managed to put together so far:
getType <K extends keyof T>(key: K): string {
type property = T[keyof T]
// I am uncertain about how to proceed from here since utilizing T as a value seems restricted
}
MWE (Minimal Working Example):
type Config {
database_host: string,
database_pass: string | undefined,
}
const defaultConfig: Config = {
database_host: 'host',
database_pass: undefined
}
const config = ConfigBuilder<Config>.resolve(defaultConfig, new EnvironmentVars(), new YamlFiles(['../path/to/yaml']))
class ConfigBuilder<T> {
public resolve(...): T {
// key from default: string
const configKey: keyof ConfigType = key as keyof ConfigType
if (foundValues.hasOwnProperty(key.toUpperCase())) {
config[configKey] = this.parse(configKey, foundValues[key])
}
}
private parse<K extends keyof ConfigType>(key: K, value: any): ConfigType[K] {
const type = this.getConfigKeyType(key)
if (this.parserDictionary[type]) {
return this.parserDictionary[type].parse(value)
}
throw Error(`Could not find parser for type ${type}`)
}
private getConfigKeyType<K extends keyof ConfigType>(key: K): string {
type configItems = ConfigType[keyof ConfigType]
}
}
// resulting in config object:
// {
// database_host: 'host',
// database_pass: 'pass'
// }
It is possible that none or either of the environment variables or parsed files could provide the database_pass
value.