我查看了类似的问题here here here和here,到目前为止,这些问题并没有帮助解决我的问题。抱歉,如果有重叠我无法提取。
我很难解释我的问题,所以这是我的最佳尝试。
我需要使用泛型提取特定键处的对象值的类型...
我将尝试设置一个最小的示例来展示我的问题。
我有一个通用类型
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
。
这可能吗?