【发布时间】:2021-07-04 23:51:38
【问题描述】:
此函数将深度嵌套的属性添加到对象,将格式为 'a.very.ddep.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;
}
它在 Javascript 中运行良好,但在 Typescript 中我收到错误 Type 'string' cannot be used to index type 'B' 试图分配 accum[property]。
通常我可以通过创建另一个具有交集类型的对象来避免改变 acc,但使用 reduce 表明我必须改变 acc insude 回调以获得最终结果。
(accum as B & { [property: string]: obj | V })[property] = isLastProperty ? value : {}; 也不起作用,给我错误type 'string' cannot be used to index type 'B & { [property: string]: obj | V; }
那有什么办法呢?
【问题讨论】:
标签: typescript object mutation