I have an array filled with objects containing keys name
and value
. My goal is to merge these objects into a single object, where the keys correspond to the name
property and the values correspond to the value
property of the input objects.
type Input = { name: string, value: any }[]
type Output = Record<string, any> // Key-value object { [name]: value }
const input: Input = [
{ name: 'name', value: 'Michal' },
{ name: 'age', value: 24 },
{ name: 'numbers', value: [4, 7, 9] }
]
const getOutput = (input: Input): Output => {
return input.reduce((output, record) => ({ ...output, [record.name]: record.value }), {})
}
// The output is: { name: 'Michal', age: 24, numbers: [4, 7, 9] }
const output: Output = getOutput(input)
The provided example works correctly, but it uses the Record<string, any>
type for the output. This results in loss of type information for the values. Is there a way to achieve this transformation while preserving the types?
output.age.length // This should trigger a TypeScript error as `number` does not have a `length` property
output.numbers.length // Should be 3
output.address // This should result in a TypeScript error as `input` does not have an `address` property