从通用类型中获取类型 属性

Fetch type of property from a generic type

我正在写一些东西,我需要在给定类型上获得 属性 的类型:

type FooBarType {
    foo: string,
    bar: number
}

函数看起来像这样:getType<K extends keyof T>(key: K): string,这样以 foo 作为参数调用函数的输出将是 string:

getType<FooBarType>('foo' as as keyof FooBarType) // string

此时我没有泛型的实现,所以使用索引访问类型似乎行不通?

这可能吗?

到目前为止我有这个:

getType <K extends keyof T>(key: K): string {
    type property = T[keyof T]
    // not sure how to continue here as I can't use T as a value
}

MWE:

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 {
     // from default: key: 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]

    }

}

// config {
//     database_host: 'host',
//     database_pass: 'pass'    
// }

或者 none 环境。 vars 或解析后的文件可以提供 database_pass 值。

如评论中所述,您已经可以使用 FooBarType['foo']

如果您希望以编程方式使用输入:

interface FooBarType {
    foo: string;
    bar: number;
}

const obj: FooBarType = {
   foo: '',
   bar: 1
}

function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
   return obj[key];
}

getValue(obj, 'foo'); // return string value
getValue(obj, 'bar'); // return number value