简体   繁体   English

通过传入的参数动态查找 TypeScript 对象值

[英]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?通过传入的 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 loglog.totalsType应该从log给我serviceCode的值

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现在,当尝试执行log.totalsType ,它将查找log.totalsType的值作为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 :但是,如果我做对了,要从数组中获取内部字段的类型,您必须使用keyof 运算符和查找类型

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游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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