首页 > 解决方案 > tslint:使用 reduce 构建对象时无对象突变

问题描述

我想以reduce这种方式构建一个对象:

const result = [1, 2].reduce((partialResult, actualValue) => {
    // define someKey and someValue
    partialResult[someKey] = someValue;
    return partialResult
}, {});

但是,我收到以下 tslint 错误:

Modifying properties of existing object not allowed. (no-object-mutation)

我该如何解决这个问题?

标签: javascripttypescript-typingstslint

解决方案


要么修改代码,这样你就不会改变对象,这意味着你每次都必须复制它:

const result = [1, 2].reduce((partialResult, actualValue) => {
    return {
      ...partialResult,
      [someKey]: someValue,
    }
}, {});

或禁用 lint 规则(如果您一般喜欢 lint 规则,则针对此特定行,或者如果您认为这是不必要的限制,则全局禁用)


推荐阅读