Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 从泛型类型获取属性的类型_Typescript_Typescript Generics - Fatal编程技术网

Typescript 从泛型类型获取属性的类型

Typescript 从泛型类型获取属性的类型,typescript,typescript-generics,Typescript,Typescript Generics,我在写一些东西,需要获取给定类型的属性类型: type FooBarType { foo: string, bar: number } 函数如下所示:getType(key:K):string,使用foo作为参数调用函数的输出将是string: getType<FooBarType>('foo' as as keyof FooBarType) // string getType('foo'作为FooBarType的键)//string 目前我还没有泛型的实现,所

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

type FooBarType {
    foo: string,
    bar: number
}
函数如下所示:
getType(key:K):string
,使用
foo
作为参数调用函数的输出将是
string

getType<FooBarType>('foo' as as keyof FooBarType) // string
getType('foo'作为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
}
getType(键:K):字符串{
类型属性=T[keyof T]
//我不知道如何在这里继续,因为我不能使用t作为值
}
MWE:

类型配置{
数据库\u主机:字符串,
数据库_pass:字符串|未定义,
}
const defaultConfig:Config={
数据库_主机:“主机”,
数据库_pass:未定义
}
const config=ConfigBuilder.resolve(defaultConfig,new EnvironmentVars(),new yamlfile(['../path/to/yaml']))
类ConfigBuilder{
公共决议(…):T{
//来自默认值:key:string
const configKey:keyof ConfigType=key作为keyof ConfigType
if(foundValues.hasOwnProperty(key.toUpperCase())){
config[configKey]=this.parse(configKey,foundValues[key])
}
}
私有解析(键:K,值:any):ConfigType[K]{
const type=this.getConfigKeyType(键)
if(this.parserDictionary[type]){
返回此.parserDictionary[type].parse(值)
}
抛出错误(`找不到类型${type}`的解析器)
}
私有getConfigKeyType(键:K):字符串{
类型configItems=ConfigType[keyof ConfigType]
}
}
//配置{
//数据库_主机:“主机”,
//数据库_pass:“pass”
// }

要么是,要么不是。VAR或解析的文件可以提供
数据库\u pass

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

如果您希望以编程方式输入,请键入:

接口FooBarType{
foo:string;
条:数字;
}
常量对象:FooBarType={
福:'',
酒吧:1
}
函数getValue(对象:T,键:K):T[K]{
返回obj[键];
}
getValue(obj,'foo');//返回字符串值
getValue(对象,'bar');//返回数值

FooBarType['foo']
将已经返回
string
。@ChristianIvicevic我如何通过编程访问它?由于类型脚本类型在编译期间被擦除,通常在运行时无法获取此信息(除非您使用带有更多元数据的反射)如果您感兴趣的类型不是一般的JS类型。我想知道为什么您首先要在运行时查询类型?通常情况下,这是不必要的。@ChristianIvicevic我正在基于环境变量构建一个对象,其中所有内容都以字符串的形式出现,具有键入内容的能力自然会使事情变得更简单。我有一个默认配置,它可能有一些未定义的东西,并留待环境稍后添加配置,但我希望避免有一个大的配置文件,其中列出了进程和默认以及其他输入设备。您能否提供一个MWE,说明您特别想用这个
getType
方法做什么?具体显示了您希望如何使用此方法的返回值,因为我认为您希望执行一些不合理的操作。我不认为OP希望访问实际值,而是希望字符串化类型,因此
getValue(obj,'foo')==='string'
等,基本上是运行时的元编程/反射。
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'    
// }