[英]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.