在打字稿中使用 propertyPath 对象似乎无法识别数组中的属性

问题描述 投票:0回答:1

所以我正在查看这段代码,它似乎从未工作过。它基本上是在 json 中查找路径并更新其值。

所以它使用 lodash,当我使用它时,它期望的类型是:

type PropertyPath = Many<PropertyName>;
/** Common interface between Arrays and jQuery objects */

这段代码使用了这种类型,如下所示:

import { PropertyPath, set } from 'lodash';

export async function setConfig(
  service: string,
  path: PropertyPath,
  value: number | boolean | string
) {
  const config: Record<string, unknown> = await getConfig(
    SERVICES[service]
  );

  set(config, path, value);
...// more code to update the config but the issue is with the above
})

所以在调用这个方法的代码中,是这样的:

  const epic = ['epic', 'reprint', 'enabled'];
  await setConfig('gaming', epic, true);

因此,基于这个示例,我们希望在游戏服务中,我们可以将位于此 json 路径中的标志更改为 true。

但是,我注意到它从未改变标志。我确实有一种解决方法,不使用属性路径类型来更新标志,但由于此代码在很多地方使用,我希望如果有人知道如何正确传递此 PropertyPath 类型的路径值,以便我们可以通过这种方式更新标志。

typescript lodash
1个回答
0
投票
epic.reprint.enabled

的形状的情况下,这就是您按照您定义的方式更新该标志的形状。

config

假设以上是正确的配置形式,请运行下面的代码片段更新其值。

config = { epic:{reprint:{enabled:false}} }

const config = {
epic:{reprint:{enabled:false}}
}
console.log("before setting", config.epic.reprint.enabled)
const result = _.set(config,["epic", "reprint","enabled"], true)


console.log("returned from set", result.epic.reprint.enabled)
console.log("mutated object", config.epic.reprint.enabled)
因此,调试应用程序的第一步是验证 
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

 的结构
    

© www.soinside.com 2019 - 2024. All rights reserved.