I have a task to create a function called indexById
that will accept an Array
of objects. Each object in the array will contain a unique id
property and may also have different value
properties.
The desired outcome is to get an object
where the keys are the id
values from the array and the corresponding values are the objects themselves, as shown in the example below.
The input array can be directly passed to the function or defined as const
.
Implementing the logic in JavaScript is simple. But how can we ensure type safety for the output?
output = getIndexById([
{
id: '1',
value: 'abc'
},
{
id: '2',
value: 123
},
{
id: '3',
value: {someProp: 3}
}
])
//expected output
const output = {
'1': {
id: '1',
value: 'abc'
},
'2': {
id: '2',
value: 123
},
'3': {
id: '3',
value: {someProp: 3}
}
}
output.3.value.someProp // typescript should know this is number