What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available:

type DataA = {
  percent: string;
  exchange: string;
};

type DataB = {
  price: number;
  exchange: string;
};

I'm puzzled as to why TypeScript gives errors when I try to use both types together:

const sumData = (
  assets: DataA[] | DataB[],
  summedBy: string,
  total: string
) => {
  const uniqueMap = assets.reduce((acc, el: DataA | DataB) => {
    if (acc.has(el[summedBy])) {
      acc.set(el[summedBy], {
        ...acc.get(el[summedBy]),
        [total]: acc.get(el[summedBy])[total] =
          +acc.get(el[summedBy])[total] + parseFloat(el[total])
      });
    } else {
      acc.set(el[summedBy], el);
    }

    return acc;
  }, new Map());

  return [...uniqueMap.values()];
};

However, there are no errors when I combine the two types into a single shape:

type CombinedShape = DataA | DataB;

Why does this discrepancy occur? https://codesandbox.io/s/16vzvqqv3 (Errors.ts and NoErrors.ts)

Answer №1

When a combination of arrays is declared as assets

assets: IData[] | IRow[]

The function reduce() behaves differently depending on the array type it is applied to: for an array of IData[], reduce() accepts a callback that takes an IData element, while for an array of IRow[], the callback receives an IRow element.

The error message - "Cannot invoke an expression whose type lacks a call signature" - indicates that the compiler may not recognize the possibility of calling reduce() on a union type, even when the appropriate callback types are provided.

There is an open issue related to this problem on GitHub:

This is currently by design because we don't synthesize an intersectional call signature when getting the members of a union type -- only call signatures which are identical appear on the unioned type

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

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

Tips for safely storing JWT tokens in a react/next.js app:

After a valid user login following proper registration through REST API, I am looking for the best way to store the JWT token that is generated. I have researched various methods of storing JWT on the client side, including local storage, session storage, ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...

error encountered in ajax contact form due to issue with select element

I'm experiencing an issue with my ajax contact form, where the input field and select element are not providing the expected results. This is the HTML Form Code (with "name" as the input and "iphone" as the select element) <div id="contact_form" ...

Mysterious python eccentricity requiring clarification

I am intrigued by a peculiar behavior in Python that I am trying to comprehend. While it doesn't seem like a bug, the reason behind this behavior eludes me. My goal is to load a group of images into a list and then manipulate them. Let's take a ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Should one consider using the Express app.use() method within an asynchronous callback function?

Seeking advice on a recommended best practice. I recently developed an Express server that generates a JWT and sends it to the client whenever they hit an API endpoint. To maintain modularity, I separated the route handler into its own module and exporte ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Exploring the use of jQuery/JS for parsing and working with JSON

Hi everyone, I need some assistance with displaying data from an array created by a PHP file using JS/jQuery. Currently, I am working on implementing a points system for ZetaBoards which you can check out here. The points will be shown below the user' ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Transferring information to the specified link using AJAX and PHP

I'm having trouble sending data to a link that I click on. Whenever I try, I just end up with an undefined index error in my PHP file. <a href="output.php"> Click me </a> ('a').click(function(){ href = "output.php"; ...

Guide for populating the chosen item in a combobox when the form control option has various parameters

I need help populating the selected saved item into the form control. <select class="form-control"> <option data-parameter-id="685" data-parent-id="1052" data-aggregation-id="null" data-aggregation-parameter="null">ABC</option> & ...

Reactjs button only responds on the second click instead of the first tap

Currently, I am working on a Reactjs/nextjs project and have a video with audio button on my page. There are two things that I want to achieve: 1) I would like the button to have the "bi bi-volume-mute" class by default instead of "bi bi-volume-down". 2) W ...

Implementing an Angular function to close a window when clicking outside of it

I was browsing YouTube and came across a tutorial on how to create a directive that closes a window when clicking outside of it. However, I'm facing an issue with implementing this in my project. I built a simple to-do list application with the abilit ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

"Which is the better choice for a Django application's for loop: views.py or

I'm in the process of creating a Django app that features a word list. The app currently utilizes a speech function to inform the user of the first word on the list. The user is then able to record an audio clip of a word they say, which is converted ...

Tutorial on React JS and Python Django: Understanding the concept of an infinite loop in componentDidUpdate

I'm currently going through an online video tutorial that teaches how to create a CRUD full-stack app using React, Django, and SQLite. However, I've encountered an issue with fetching table data causing an infinite loop. It appears that the probl ...