I have looked at similar questions here here here and here that so far have not helped resolve my issue. Apologies if there is overlap that I was not able to extract.
I'm having a really tough time explaining my issue, so here goes my best attempt.
I need to extract the type of an objects value at a particular key, using generics...
I'll try to setup a minimal example showcasing my issue.
I have a generic type
export type Column<T> = {
title: string
prop: keyof T
render?: (val: any /* needs to be type of T[prop] */, item: T) => any
}
I have a render
function on that generic type that gets called with two parameters: the value of the object at the provided property prop
, and also the full object. Right now I have the val
ue typed as an any, but I would love it if that could be inferred, since we have the prop
stated as a keyof T
. So I need val
to be the value of T
at property prop
which happens to be a keyof T
.
Example:
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
)
}]
Hopefully that showcases a good example. Basically I would love it if the render
function's first parameter was type aware, since we are passing in the property of the object as prop
.
Is this possible?