简体   繁体   English

通用接口内的 Typescript 函数来推断参数类型

[英]Typescript function inside generic interface to infer argument type

Lets say I have an interface that accepts a generic:假设我有一个接受泛型的接口:

interface ObjectKey<T extends {}>{
   key: keyof T
   doSomethingWithKey: (value: any) => void
}

Using it like this:像这样使用它:

interface User {
   name: string,
   age: number,
   archived: boolean
}

const nameKey: ObjectKey<User> = {
   key: 'name', 
   doSomethingWithKey: (value) => console.log(value) // I want to infer value type here
}

As mentioned above i want to infer the 'value' argument type.如上所述,我想推断“值”参数类型。 Something like this:像这样:

interface ObjectKey<T extends {}>{
   key: keyof T
   doSomethingWithKey: (value: T[key]) => void
}

How can I achieve that?我怎样才能做到这一点?

I tried something like:我试过类似的东西:

interface ObjectKey<T extends {}>{
   key: keyof T
   doSomethingWithKey: (value: { [Property in keyof T]: T[Property] }[keyof T]) => void
}

But it returns all available types of T. For example if we use User interface, 'value' argument would be 'string |但它会返回所有可用的 T 类型。例如,如果我们使用用户界面,“值”参数将是“字符串 | number |编号 | boolean'布尔值'

Playground link 游乐场链接

We can make ObjectKey a union type of all possible combinations by mapping over the object keys我们可以通过映射对象键使ObjectKey成为所有可能组合的联合类型

type ObjectKey<T extends {}> = {
   [K in keyof T]: {
      key: K, 
      doSomethingWithKey: (value: T[K]) => void
   }
}[keyof T]

interface User {
   name: string,
   age: number,
   archived: boolean
}

const nameKey: ObjectKey<User> = {
   key: 'age', 
   doSomethingWithKey: (value) => console.log(value)
}

Playground 操场

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM