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

TypeScript reduce处理对象报错:Storybook控件隐藏的类型问题

问题解决方案

错误原因分析

  1. 第一个错误:reduce的泛型参数误用了Props接口——Props定义的是包含accumulator和value的复合结构,并非reduce最终要返回的控件配置对象类型,初始值{}自然无法匹配该类型。
  2. 第二个错误:由于controlsToOmitArgTypes被错误标记为Props类型,而Props不是纯键值对的对象类型,导致在argTypes中展开时触发类型检查错误。

修正后的代码

const controlsToOmit: string[] = [
  'connectedLeft',
  'connectedRight',
];

// 定义单个隐藏控件的类型
type OmittedControl = {
  table: {
    disable: true;
  };
};

// 定义最终生成的控件配置对象类型
type OmittedControls = Record<string, OmittedControl>;

const controlsToOmitArgTypes = controlsToOmit.reduce<OmittedControls>(
  (accumulator, value) => ({
    ...accumulator,
    [value]: {
      table: {
        disable: true,
      },
    },
  }),
  {} as OmittedControls // 初始值断言为目标类型
);

export default {
  title: 'Components/Buttons/ButtonMeta',
  component: ButtonMetaComponent,
  argTypes: {
    ...controlsToOmitArgTypes, // 类型匹配,可正常展开
  },
};

简化写法(可选)

如果不想额外定义类型,也可以直接用具体结构作为泛型参数,代码更简洁:

const controlsToOmit: string[] = [
  'connectedLeft',
  'connectedRight',
];

const controlsToOmitArgTypes = controlsToOmit.reduce<Record<string, { table: { disable: true } }>>(
  (accumulator, value) => ({
    ...accumulator,
    [value]: {
      table: {
        disable: true,
      },
    },
  }),
  {} as Record<string, { table: { disable: true } }>
);

export default {
  title: 'Components/Buttons/ButtonMeta',
  component: ButtonMetaComponent,
  argTypes: {
    ...controlsToOmitArgTypes,
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:05:28