I have an array of objects with keys name
and value
. I would like to convert this array into single object, where keys are name
and values are value
properties from 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 }), {})
}
// Output is: { name: 'Michal', age: 24, numbers: [4, 7, 9] }
const output: Output = getOutput(input)
The example above is working, however I used Record<string, any>
type for output. That means I lost types of values. Is there any way to perform this transformation, but keep types?
output.age.length // Should be TS error, `number` has no `length` property
output.numbers.length // 3
output.address // Should be TS error, `input` has no `address` property