TypeScript:使用keyof T

时间:2020-11-10 22:43:32

标签: typescript generics keyof

我查看了类似的问题here here herehere,到目前为止,这些问题并没有帮助解决我的问题。抱歉,如果有重叠我无法提取。

我很难解释我的问题,所以这是我的最佳尝试。

我需要使用泛型提取特定键处的对象值的类型...

我将尝试设置一个最小的示例来展示我的问题。

我有一个通用类型

export type Column<T> = {
  title: string
  prop: keyof T
  render?: (val: any /* needs to be type of T[prop] */, item: T) => any
}

我在该泛型类型上有一个render函数,该函数用两个参数调用:提供的属性prop上的对象的值以及完整的对象。现在,我将val ue键入为any,但是如果可以推断出来,我会喜欢的,因为我们将prop声明为keyof T。因此,我需要val作为属性T上的prop的值,该属性恰好是keyof T

示例:

type Car = {
  model: string
  passengerCount: number
}

const columns: Column<Car>[] = [{
  title: 'Model',
  prop: 'model', // type aware as keyof T (keyof Car),
  render: (val: any /* I want this to be type aware as a string */, item: Car): string => (
    `Model: ${val}` // arbitrary for example purposes
  )
}, {
  title: 'Number of passengers',
  prop: 'passengerCount', // type aware as keyof T (keyof Car),
  render: (val: any /* want this to be type aware as a number */, item: Car): string => (
    `${val} passengers` // arbitrary for example purposes
  )
}]

希望这是一个很好的例子。基本上,如果render函数的第一个参数是类型敏感的,我会喜欢的,因为我们将对象的属性传递为prop

这可能吗?

0 个答案:

没有答案