I created a function that takes a specific array of objects and returns a copy of this array but with changed key names and values.
I cannot figure out how to get rid if this one any in the code below and still get this function to work.
If I set result type to ResultType I get a whole bunch of errors, i.e
- Type '{}' is not assignable to type 'ResultType'. '{}' is assignable to the constraint of type 'ResultType', but 'ResultType' could be instantiated with a different subtype of constraint 'ObjectType'.
- Type 'string' cannot be used to index type 'ResultType'.
- Type 'string' is not assignable to type 'ResultType[Extract<keyof InputType, string>]'.
type TMap<T> = Map<T, number | string>
type ObjectType = Record<string, any>
export const mapArrayOfObjectsKeysAndValues = <InputType extends ObjectType, ResultType extends ObjectType>(
objectArray: InputType[],
keyMap: TMap<string>,
valueMap: TMap<InputType[keyof InputType]>,
): ResultType[] => {
return objectArray.map(object => {
const result: any = {} // I would like to get rid of this one any
for (const key in object) {
const mappedValue = valueMap.get(object[key])
const mappedKey = keyMap.get(key)
switch (true) {
case !!(mappedValue && mappedKey):
result[mappedKey] = mappedValue
break
case !!(!mappedValue && mappedKey):
result[mappedKey] = object[key]
break
case !!(mappedValue && !mappedKey):
result[key] = mappedValue
break
default:
result[key] = object[key]
}
}
return result
})
}