Typescript encounters an overload error on the Accumulator argument while using reduce operation

I encountered the following code snippet:

const foo = (
  fields: {
    [key: string]: string,
  }
) => {
  const { one, two } = Object.values(fields).reduce(
    (acc, field) => {
      if (isOne(field)) {
        return { ...acc, two: [...acc.two, field] }
      }
      return { ...acc, one: [...acc.one, field] }
    },
    { one: [], two: [] }
  )

  // ...
}

However, I am consistently getting an error message regarding:

Argument of type '(acc: { one: never[]; two: never[]; }

Answer №1

When you assign an object with empty array literals to a variable, the compiler may interpret those arrays as having the type never[], which isn't very useful:

const init = { one: [], two: [] };
/* const init: {
    one: never[];
    two: never[];
} */

init.one.push("whoops"); // error!

This limitation in TypeScript design has been noted in microsoft/TypeScript#29398. It seems that the compiler assigns a type too early to empty array literals, leading to unexpected behaviors at times.

If the compiler infers a type for a value that is not what you want, consider annotating or asserting the type of that value explicitly:

const init2: { one: string[], two: string[] } = { one: [], two: [] };
init2.one.push("okay"); // okay

In your code snippet using reduce(), the compiler assumes the accumulator's type is {one: never[], two: never[]}. This conflicts with the return type of the reducer callback, resulting in an error due to overloaded functions.

To resolve this issue, specify the generic type parameter explicitly when calling reduce():

const { one, two } = Object.values(fields).
  reduce<{ one: string[], two: string[] }>( // <-- specify here
    (acc, field) => {
      if (isOne(field)) {
        return { ...acc, two: [...acc.two, field] }
      }
      return { ...acc, one: [...acc.one, field] }
    },
    { one: [], two: [] }
  )

By setting the documented type of the accumulator to {one: string[], two: string[]}, the call to reduce() no longer throws an error because the return value matches the expected type.


I hope this explanation helps you make sense of the issue and good luck with your coding!

Playground link to code

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

Exploring multiple states within an interval function in React Native

I'm struggling to find the right words for this question. I've encountered an issue where I need to constantly check and update a complex state object within an interval loop in my program. To simplify, let's say it consists of just a counte ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Is there an issue with type guards not functioning as expected within async functions in Typescript?

As I work on implementing an authentication function for user roles using TypeScript and Firebase/Store, I've come across a peculiar issue related to type guards in async functions, especially with the use of .then(). Here is a brief snippet showcasi ...

Emphasize a Row Based on a Certain Criteria

One of the challenges I am facing is how to emphasize a specific row in a table based on certain conditions. Currently, I am utilizing Jqxgrid and have made some modifications in the front-end to achieve the highlighting effect: TypeScript: carsDataAgain ...

No data found in the subrow of the datasource after the filter has been

I am working with a material table that has expandable rows. Inside these expanded rows, there is another table with the same columns as the main table. Additionally, I have implemented filters in a form so that when the filter values change, I can update ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Recursively map elements of a TypeScript array to keys of an object

I am looking to create a structured way to specify paths for accessing objects, ensuring that the path is correctly typed based on the object type. Let me illustrate with an example. Consider the following data: const obj = { name: 'Test', ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

The anticipated data type is derived from the attribute 'value' defined within the 'IntrinsicAttributes & ProviderProps<IProductContext>' type

During the creation of an e-commerce website, I decided to use React Typescript. However, I encountered an issue with Contexts while trying to export my state in the Provider value. Thank you for any assistance provided. ERROR Type '{ products: IP ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set. Consider the following three classes: class A { p1: C constructor() { p1 = new C("A") } } class B { p2: ...

Issue accessing page from side menu in Ionic 2 application

I am experiencing an issue where the page does not open when I click on it in the side menu. Here is my app.component.ts file: this.pages = [ { title: 'NFC Page', component: NfcPage, note: 'NFC Page' }, ...

Leveraging TypeScript to sort and extract specific elements from two arrays

Given two arrays, I am looking to identify the elements in array2 that match elements in array1 based on a specific property. The arrays are structured as follows: var array1 = [ {"myId": 1, "text": "a"}, {"myId& ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...