This particular function is designed to add a deeply nested property to an object by taking a string argument in the format of 'a.very.deep.property'.
function nest<B extends obj, V = unknown>(
target: B,
structure: string,
value: V,
) {
const properties = structure.split('.');
const result = target;
properties.reduce((acc, property, i, arr) => {
const isLastProperty = i === arr.length - 1;
if (!(property in acc))
acc[property] = isLastProperty ? value : {};
return acc[property];
}, target);
return target;
}
While this function works well in JavaScript, it encounters an error in TypeScript where
Type 'string' cannot be used to index type 'B'
when attempting to assign accum[property]
.
One could typically avoid mutating acc
by creating another object with intersection type, however using reduce
implies that mutation of acc inside the callback is necessary to obtain the final result.
(accum as B & { [property: string]: obj | V })[property] = isLastProperty ? value : {};
also does not solve the issue, resulting in the error type 'string' cannot be used to index type 'B & { [property: string]: obj | V;
.
What would be the best approach in this situation?