简体   繁体   中英

Dynamically finding TypeScript object values through passed in parameters

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM