You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改reduce函数解决逗号运算符使用不当的ESLint错误?

解决TypeScript reduce中「Unexpected use of comma operator no-sequences」错误

你遇到的错误是因为ESLint的no-sequences规则禁止在return语句中用逗号运算符串联多个表达式。以下是几种可行的修改方案:

方案一:用块级语句拆分赋值与返回

这是最直接的修改方式,先给累加器赋值,再单独返回累加器:

const defaultKeys = ["a", "b", "c"];

const defaultKeysObj = defaultKeys.reduce(
  (acc: { [key: string]: number }, curr) => {
    acc[curr] = 0;
    return acc;
  },
  {} as { [key: string]: number }
);

注意给初始值{}添加类型断言,避免TypeScript推断出错误的累加器类型。

方案二:使用对象展开语法(不可变写法)

如果偏好函数式编程的不可变风格,可以通过对象展开创建新对象返回:

const defaultKeys = ["a", "b", "c"];

const defaultKeysObj = defaultKeys.reduce(
  (acc: { [key: string]: number }, curr) => ({
    ...acc,
    [curr]: 0
  }),
  {}
);

用括号包裹对象字面量,避免被解析为函数体块。

方案三:使用Object.assign

和对象展开逻辑类似,通过Object.assign修改并返回累加器:

const defaultKeys = ["a", "b", "c"];

const defaultKeysObj = defaultKeys.reduce(
  (acc: { [key: string]: number }, curr) => Object.assign(acc, { [curr]: 0 }),
  {} as { [key: string]: number }
);

内容的提问来源于stack exchange,提问作者Owenn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:40:33