0

not sure if the title is misleading or actually is asking what I want: I am trying to get an Object's element value, but the tricky thing is that the element's name is being passed in through a function...

Here is a simplified sample of my code, hope it's clear what I am trying to do

export interface logItem {
   id: string
   procedure: string
   units: string
   serviceCode: string
}

function calculateTotalsBasedOnType(
   logItems: Array<logItem>
   totalsType: string
): totals {
   ... log.totalsType ...
}

what's the way to go about finding the specific log's element value through the passed in totalsType?

Here is an example method for this

calculateTotalsBasedOnType(logItems, 'serviceCode')

the line log.totalsType should give me the value of the serviceCode from the log

Stevan Najeeb
  • 101
  • 1
  • 12

2 Answers2

0

In order for typescript to understand that the passed in parameter is a element key of an object you need to make that parameter a string literal type

type TotalTypeValue = 'serviceLine' | 'procedure'

function calculateTotalsBasedOnType(
   logItems: Array<logItem>
   totalsType: TotalTypeValue
)

now when trying to do log.totalsType it will look for the value of totalsType to be one of the elements in the log

Stevan Najeeb
  • 101
  • 1
  • 12
0

The question is pretty vague on the subject what exactly you're trying to achieve. But if I got it right, to get the type of the inner field from array you'll have to use keyof operator and lookup types:

function calculateTotalsBasedOnType<T, K extends keyof T>(
   logItems: Array<T>,
   totalsType: K
): T[K] {
   return logItems[0][totalsType] // just random element from the source array
}

playground link

aleksxor
  • 7,535
  • 1
  • 22
  • 27