1

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 value 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?

BradStell
  • 371
  • 3
  • 17
  • It looks like we have been solving the exact same problem? (Material ui table?) – dwjohnston Nov 10 '20 at 22:52
  • @dwjohnston this does seem to be the same issue we are having. Did the provided answer solve the issue? – BradStell Nov 10 '20 at 22:55
  • Yes. 1234123451234 – dwjohnston Nov 10 '20 at 22:56
  • @dwjohnston I'm going to have to stare that one down for a moment. It's a bit hard to understand. But thank you for this. – BradStell Nov 10 '20 at 22:59
  • If you look at the original question - I think that's pretty straight forward and pretty similar to what you've got. As it is, I've just copied in the answer and happy to use it - I don't have my head around it at this point. – dwjohnston Nov 10 '20 at 23:00

0 Answers0