Home > Enterprise >  Typescript: reduce object of objects
Typescript: reduce object of objects

Time:11-16

Struggling a bit getting a reduce function working with typescript - both the types and the return value - omitting some controls from storybook (added two TS errors in the code marked ** ERROR **)

Can anyone advise of the correct solution and how I get rid of the messages?

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

interface Props {
  accumulator: {
    [key: string]: {
      table: {
        disable: true;
      };
    };
  };
  value: string;
}

const controlsToOmitArgTypes = controlsToOmit.reduce<Props>(
  (accumulator, value) => ({
    ...accumulator,
    [value]: {
      table: {
        disable: true,
      },
    },
  }),
  {} ** Argument of type '{}' is not assignable to parameter of type 'Props' **
);

export default {
  title: 'Components/Buttons/ButtonMeta',
  component: ButtonMetaComponent,
  argTypes: {
    ...controlsToOmitArgTypes, ** Spread types may only be created from object types. **
  },
};

The controlsToOmitArgTypes returns the following object

{
    "connectedLeft": {
        "table": {
            "disable": true
        }
    },
    "connectedRight": {
        "table": {
            "disable": true
        }
    },
}

CodePudding user response:

The type argument of reduce is used to indicate the return type

You want to return a structure like:

[key: string]: {
  table: {
    disable: true;
  };
};
const controlsToOmit: string[] = [
  'connectedLeft',
  'connectedRight',
];

interface Props {
  [key: string]: {
    table: {
      disable: true;
    };
  };
}

const controlsToOmitArgTypes = controlsToOmit.reduce<Props>(
  (accumulator, value) => ({
    ...accumulator,
    [value]: {
      table: {
        disable: true,
      },
    },
  }),
  {}
);
  • Related