Dealing with Typescript: Reducing an object containing other objects

Having some difficulties implementing a reduce function with TypeScript - struggling with types and return value. Facing issues with omitting controls from Storybook, causing two TypeScript errors indicated in the code marked ** ERROR **

Seeking advice on the correct solution and how to eliminate these error 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 produces the following object

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

Answer №1

The type parameter of the reduce function specifies the return type

If you wish to produce a structure like this:

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

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

const excludedControls = exclusionList.reduce<Properties>(
  (result, item) => ({
    ...result,
    [item]: {
      table: {
        disable: true,
      },
    },
  }),
  {}
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript plugin specifically designed to enable playback of media content, such as videos from

I am working on a spring-based project and I require the ability to play audio/video in various formats similar to YouTube. I am currently searching for a free JS plugin that would be the best fit for my needs. Any suggestions or recommendations would be ...

How do Angular and NestJS manage to dynamically resolve injection tokens during runtime using the TypeScript type hints provided at compile time?

Frameworks such as Angular and NestJS in TypeScript utilize dependency injection by converting TypeScript type hints into injection tokens. These tokens are then used to fetch dependencies and inject them into constructors at runtime: @Injectable() // < ...

Encountering a 'scheduler flush execution error' and an Uncaught TypeError due to VueJS and Axios integration

After carefully examining my code, I have pinpointed the cause of this error to the following line: treeNodes.value = documentStore.convertToTree((await axios.get('/File')).data); Initially, I receive a warning: Vue warn]: Unhandled error during ...

Is it possible to assign a class to the initial word within a designated class?

How can I customize the first and second word of a specific class in my code? This is an example of my current code: <h2 class="content-heading">Latest News</h2> I would like to achieve something similar to this: <h2 class="content-headi ...

Display the checkbox as selected using AngularJS

I have already submitted a form with a checkbox value. Now, I am trying to display the checkbox as "checked" using AngularJS based on the value retrieved from the data source. Can someone guide me on how to achieve this? ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

What is the proper way to implement a function with a value formatter when the column definition is already predefined within quotation marks in AG-Grid?

When working with JSON data that specifies columnDefs and uses valueFormatters as a function, it is essential to correctly format the valueFormatter. For instance, if the JSON data reads valueFormatter: "dateFormatter" instead of valueFormatter: ...

Leveraging JavaScript within PHP script

I am currently developing a booking system that involves creating events in a table using PHP. I want to implement a script that will run when a user tries to book an event and then submits the form to PHP. This script will help me determine if the user ha ...

`Is there a way to retrieve the ID of an element upon clicking on it?`

Can you help me with a JavaScript query? I have two HTML div elements with ids of 'div1' and 'div2'. When I click on any of the divs, I want to display the id of the clicked div. Any thoughts? <div id="div1"></div> <div ...

Implementing a React app mounting functionality upon clicking an HTML button

Is there a way to mount a react application by clicking on a standard html button outside of the application itself? My index.html layout is as follows: <div id="app"></div> <button id="button-root">Live chat</butt ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Is there a way to selectively transfer attributes and behaviors from an interface to a fresh object in typescript?

Is there a way in javascript to selectively copy properties from one object to another? I am familiar with using Object.assign() for this purpose. Specifically, I am looking to extract only the properties defined within the following interface: export in ...

The next.js application utilizing a custom server is experiencing rendering issues

Expanding my knowledge to next.js, I might be overlooking a simple aspect. My goal is to implement custom routes, so I crafted a server.js file and adjusted the command in my package.json to node server.js. Below is the entirety of the server.js file: con ...

Is there a way to determine the width of a ChildNode within a React component?

In my React and Typescript project, I am working on building a carousel of tabs with varying sizes. It is important for me to accurately calculate the width of each tab in order to determine how many tabs can fit within each view. The challenge I am facing ...

Extract attributes from a string of HTML containing name-value pairs

Here is a sample string that I need to work with '<img id="1" data-name="test" src="img_01.jpg" />' My goal is to extract the attribute name and value pairs from the string, create the element, and apply these attributes. I have come up ...

What is the best way to display the current scroll percentage value?

I'm trying to update this code snippet import React from 'react' const App = () => { function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

A variant of setTimeout designed specifically for family members

I am currently working on a program that involves creating a "health" variable which decreases by random amounts at random intervals. This means that a player may encounter scenarios like the following: 5 seconds Lose 20 health 3 more seconds Lose 25 healt ...