Unleashing the full power of TypeScript: Harnessing Array.prototype.reduce with Generics

Attempting to standardize data using Array.prototype.reduce.

Puzzled by how I can bypass "type-checking" in the reduce function.

My interfaces:

interface Dict<T> {
  [key:string]: T;
}

interface InnerData {
  id: string;
  value: number;
}

interface RawData {
  innerData: InnerData[];
}

interface NormalizedData {
  innerData: Dict<InnerData>
}

Examples of how I intended to use these interfaces:

const rawData: RawData = {
  innerData: [
    {
      id: "ID_ONE",
      value: 1
    },
    {
      id: "ID_TWO",
      value: 2
    }
  ]
};

const normalizedData: NormalizedData = {
  innerData: this.noramlizeInner(rawData.innerData),
};

private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
  return innerData.reduce((acc:Dict<InnerData>, curr: InnerData) => {
    return {
      ...acc,
      [curr.id]: {
        ...curr
      }
    }
  }, {});
}

However, when I modify the normalizeInner, it still compiles and the returned value is unexpectedly incorrect.

private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
  return innerData.reduce((acc, curr: InnerData) => {      
    return {
      ...acc,
      [curr.id]: [curr]
    }
  }, {});
}

To reiterate my question, what mistake did I make in the reduce function that allows it to compile?

CodeSandBox app for demonstration: (LINK)

Answer №1

It appears that there is an issue with your Dict interface as it only accepts a single object as the property value

interface Dict<T> {
  [key:string]: T;
}

However, you are attempting to assign an array of objects

private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
  return innerData.reduce((acc, curr: InnerData) => {      // changed acc:Dict<InnerData> to acc in the signature.
    return {
      ...acc,
      [curr.id]: [curr]
              // ^ this is an array but Dict<InnerData> expects it to be a single object
    }
  }, {});
}

Consider enhancing your dict to also accept an array of objects like this

interface Dict<T> {
  [key: string]: T | T[];
}

Alternatively, you can modify your reduce function to return an object instead of an array of objects

  private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
    return innerData.reduce((acc: Dict<InnerData>, curr: InnerData) => {
      return {
        ...acc,
        [curr.id]: curr
      };
    }, {});
  }

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

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

Utilize ngClass for every individual section

I have completed the implementation of all UI components, which are visually appealing. https://i.sstatic.net/hxJQr.png Here is the data structure I am using: public filters = [ { tag: 'Year', label: 'ye ...

Exploring TypeScript Decorators and the Intricacies of Circular Dependencies

Take a look at this code snippet that involves inter-dependent code using decorators. Let's walk through the workflow where the actual classes are passed for later use: The application imports and executes Parent.ts @Test(Child) triggers the import ...

the category is unspecified

As I try to deploy my code and run the build, TypeScript is throwing an error stating that 'object' is of type unknown. I am currently working on resolving this issue in my specific scenario. export default function Home() { async function send ...

Creating an enumeration within a class

I'm encountering difficulties when trying to declare an enum element within a class. Despite attempting various methods to declare the enum, I am unable to make it function properly. Here is the (non-functional) class: export class Device extends El ...

Parsing JSON in Android without specifying an array name

Can anyone help me with parsing a Json Array in Android when it does not have a name specified? Here is the array I am trying to parse: {"emp_info":[ {"id":"1","group":"1","teacher":"1"}, {"id":"2","group":"2","tea ...

Interaction of PHP and JavaScript when a new row is inserted using JavaScript

I have encountered an issue with the following PHP code snippet: PHP Code: <?php $output['house_sitting_date_yes_no']=$_POST['house_sitting_date_yes_no']; if(file_exists('../feeds/ptp-ess_landing_house.json')){ ...

Show the first and last names of users in simple text format directly retrieved from the database, not as an array

On my HTML page, I am sending the value phone to log.php: <?php $PHONE = $_POST['phone']; mysql_connect('host.com', 'user', 'pass'); mysql_select_db('userdb'); $results = mysql_query(spr ...

Serialize a Python return function to JSON format

As someone who is new to JSON and Python, I'm excited to dive into the world of working with JSON in Python. Lately, I've been tinkering with some code like this: import json def product(): itemId = 84576454 itemName = 'FGX Flanne ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

How can I efficiently perform a circular shift on a two-dimensional array?

Considering a universal perspective (without tying it to any specific programming language), I would like to discuss a shifting operation that can be applied to a 2D array. The goal is to find an efficient solution that does not rely on pointer arithmetic ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Is there a way to create a dictionary in Javascript with all keys pointing to the same value?

I have a scenario where I need to convert an array into an object like this: let arr = ['ABC', 'DEF'] The desired transformation is: let obj = {"ABC": 0, "DEF": 0} Can someone guide me on how to achieve this using ...

The error message "Property 'id' is missing on type 'T'" is indicating the absence of the 'id' property in the

I am currently working on a React component that serves as a table and is designed to handle various types of data. The structure of the component is defined as follows: type SimpleTableProps<T> = { data: Array<T>; ... }; const SimpleTabl ...

What can cause a problem with the reduce function that populates an empty object with keys in TypeScript?

I've encountered an issue with a function that is meant to reduce an object. The problem lies in using the reduce method to assign the values of acc[key] as object[key], which is resulting in errors in the code. I am trying to avoid using any specific ...

The response of C++ memory allocation when the size of the array is zero

Within my code, there exists a class named MyClass which includes a print statement within the constructor and destructor. I am currently exploring memory allocation with the new operator and have some inquiries regarding the output produced by the followi ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

What is the solution for the warning "Solid's reactivity is broken when destructuring component props"?

Just starting out with SolidJS and encountering an issue with my UI setup import { render } from "solid-js/web"; import { createSignal, Show } from "solid-js"; import { createStore } from 'solid-js/store'; function Form() { ...