简体   繁体   English

使用接口的键索引 object 而值是具有该键的返回类型的 function

[英]index an object with the keyof an interface while the value is a function with the return type of that key

Here's what I have as an interface:这是我作为界面的内容:

interface Person{
    name: string
    age: number
    hobbies: string[]
}



const processors : {[functioname: keyof Person}: (value: string)=> Person[fuctionname]} =
{
    name: (value)=>{}//must return string
    age: (value)=>{}//must return a number
}

I want the processors to be funcitons indexed by the key and return a value of the same type我希望处理器是由键索引的函数并返回相同类型的值

so if the key is name, the return type should be string like in the interface因此,如果键是名称,则返回类型应该是接口中的字符串

You need to use Type[key] construction.您需要使用Type[key]构造。

Here is an example, pay attention to the type Proc<T>这里是一个例子,注意type Proc<T>

interface Person{
    name: string
    age: number
    hobbies: string[]
}


type Proc<T> = {
    [key in keyof T]: ()=> T[key]
}

const processors : Proc<Person> =
{
    name: ()=>'',//must return string
    age: ()=>5,//must return a number
    hobbies: ()=> []
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 TypeScript 通用 function 类型参数是 object 的键值的返回类型 - How to have TypeScript generic function with type argument being keyof an object have return type of that object's key's value 具有keyof的Typescript函数不接受对象键值作为有效的keyof - Typescript function with keyof doesn't accept object key value as valid keyof 打字稿:keyof返回值的泛型类型限制 - Typescript: generic type restriction on return value of keyof 为什么`keyof object`返回never类型? - Why does `keyof object` return a never type? 函数不返回嵌套keyof的值 - Function doesn't return value of nested keyof 不能将索引访问类型与 T[Key extends keyof T] 一起使用 - Cannot use index access type with T[Key extends keyof T] Typescript:与“keyof interface”相比,“keyof typeof value”产生不同的类型结果 - Typescript: 'keyof typeof value' makes different type result compared to 'keyof interface' 在 Typescript 中键入键值对 object 并保存 object 的键 - Typed key-value-pair object in Typescript with saving keyof the object Typescript:- 使用 object 为 function 创建泛型类型,其中一个键作为值类型,返回类型是值 - Typescript :- create generic type for function taking object having one key as type of value and return type is value 使用keyof(接口)简化类型定义? - Simplify type definition with keyof (interface)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM