An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this

type AnyType = {
  name: 'A' | 'B' | 'C';
  isAny:boolean;
};

const myArray :AnyType[] =[
  {name:'A',isAny:true},
  {name:'B',isAny:false},
]

I am trying to use the reduce function on myArray to create an array based on the 'name' property only

const namesArray=myArray.reduce<AnyType['name'][]>((a,b)=>{
  return b.name;
},[])

However, I encounter a TypeScript error

(parameter) b: AnyType
BugFinder: No overload matches this call.BugFinder: 
  Overload 1 of 6, '(callbackfn: (previousValue: ("A" | "B" | "C")[], currentValue: AnyType, currentIndex: number, array: AnyType[]) => ("A" | "B" | "C")[], initialValue: ("A" | "B" | "C")[]): ("A" | ... 1 more ... | "C")[]', gave the following error.BugFinder: 
    Argument of type '(a: ("A" | "B" | "C")[], b: AnyType) => "A" | "B" | "C"' is not assignable to parameter of type '(previousValue: ("A" | "B" | "C")[], currentValue: AnyType, currentIndex: number, array: AnyType[]) => ("A" | "B" | "C")[]'.BugFinder: 
      Type '"A" | "B" | "C"' is not assignable to type '("A" | "B" | "C")[]'.BugFinder: 
        Type '"A"' is not assignable to type '("A" | "B" | "C")[]'.BugFinder: 
  Overload 2 of 6, '(callbackfn: (previousValue: ("A" | "B" | "C")[], currentValue: AnyType, currentIndex: number, array: AnyType[]) => ("A" | "B" | "C")[], initialValue: ("A" | "B" | "C")[]): ("A" | ... 1 more ... | "C")[]', gave the following error.BugFinder: 
    Argument of type '(a: ("A" | "B" | "C")[], b: AnyType) => "A" | "B" | "C"' is not assignable to parameter of type '(previousValue: ("A" | "B" | "C")[], currentValue: AnyType, currentIndex: number, array: AnyType[]) => ("A" | "B" | "C")[]'.BugFinder: 
      Type '"A" | "B" | "C"' is not assignable to type '("A" | "B" | "C")[]'.BugFinder: 
        Type '"A"' is not assignable to type '("A" | "B" | "C")[]'.

Click here to access the playground

Answer â„–1

The result returned is in the form of an array:

const NameList = myArray.reduce<AnyType["name"][]>(
  (accumulator, { name }) => [...accumulator, name],
  []
);

Another approach utilizing Array#map:

const NameList = myArray.map<AnyType["name"]>(({ name }) => name);

Answer â„–2

If your goal is to transform an array into a new array, the best approach is to utilize the myArray.map method;
However, if you have a specific requirement to use reduce, perhaps for additional filtering functionalities, ensure that the reducer callback function is properly structured.
It's crucial that the reducer function returns the accumulator value, which in this case should be an array of names;
The error message from TypeScript indicates that you are returning a single name instead of an array of names.

Here is an example combining mapping and filtering using reduce:

const namesArray = myArray.reduce<AnyType['name'][]>( ( accumulatorArr, currentValue ) => {
  if ( currentValue.isAny ) {
    accumulatorArr.push( currentValue.name );
  }
  return accumulatorArr;
}, [] );

Answer â„–3

If you are considering using Array.reduce(), this method can be helpful. However, as pointed out by @majed Badawi, achieving the same result with Array.map() is simpler.

interface DifferentType {
  category: 'X' | 'Y' | 'Z';
  hasValue: boolean;
}

const yourArray: DifferentType[] = [
  { category: 'X', hasValue: true },
  { category: 'Y', hasValue: false },
];

const categoriesArray = yourArray.reduce((x, y) => {
  x.push(y.category);
  return x;
}, [] as string[]);

REMINDER: I have made adjustments to your type declaration for convenience. Feel free to modify it according to your preference!

Answer â„–4

Give this a shot:

let arrayOfNames = myArray.reduce((accumulator, currentValue) => { 
  return currentValue.name;
}, []);

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

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

What is the best way to use setInterval with an Express application?

I've been searching online for a while, experimenting with different methods and coming up with unconventional solutions to my issue without making any progress. My main query is, how can I set an interval in my express.js application to run every 30 ...

Data structure for Highcharts:

Recently, I've been experimenting with Highcharts (http://www.highcharts.com) in a test application built on rails 3.1.1 and HAML. As someone who is still new to JavaScript, I'm striving towards achieving a seamless integration of Highcharts. Wi ...

Understanding how to retrieve a particular list item in JQuery without having the index in advance

I have a lengthy list that is broken down into various subheadings. How can I retrieve the second to last element of the list before a specific subheading, provided it is not the final element? Is it possible to do this if I know the ID of the subheading? ...

Angular integrated with DOJO application

I'm currently working on incorporating Angular into an existing DOJO application. I've set up a plunkr http://plnkr.co/edit/8pgdNwxFoxrDAQaQ4qfm?p=preview, but unfortunately, the angular module is not loading. Can anyone provide guidance on what ...

Leveraging the `--max-http-header-size` flag with ts-node

Encountered an issue when trying to use ts-node with the --max-http-header-size 15000 flag. It works fine with regular node, but unfortunately, ts-node does not support that option ...

Cipher Caesar - symbols and additional characters

I've constructed a Caesar Cipher script down below, however, I wish for the output string to contain spaces and other characters. Despite my attempts with regex, it doesn't seem to rectify the issue or maybe I'm not utilizing it correctly †...

Interactive real-time search results with clickable option through AJAX technology

Currently, I have implemented a live search feature that displays results based on what the user types in real time using the keyup function. However, one issue I encountered is that the displayed results inside the <div> tag are not clickable. Is th ...

Submitting HTML forms in SilverStripe using Ajax

I need to transfer data from a basic HTML form to a controller using Ajax, then handle the data and send a response back. Currently, my setup looks like this: HomePage.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkf ...

Updating form validation by altering input value

I'm currently utilizing JavaScript regular expressions for form validation in my project. After successfully completing the validation without any errors, upon clicking the submit button, I want the form to be submitted and change the submit value to ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Stop repeated form submissions in Angular using exhaust map

How can we best utilize exhaust Matp to prevent multiple submissions, particularly when a user is spamming the SAVE button? In the example provided in the code snippet below, how do we ensure that only one submission occurs at a time even if the user click ...

Issue with Element Not Displaying During Page Load with Quick AJAX Request

I attempted to display a loading gif while making an ajax request that takes a long time to respond, and then hide the loading gif once the response is received. Here is the code snippet : $('.loading-gif').show(); $ajax({url:'',async ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

Passing a selected option in a select box to another website is achievable using JavaScript

I'm still learning JavaScript and I would like to have a user be directed to another page when they select an option from a dropdown menu. Any suggestions on how to accomplish this? ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

I am encountering an issue with this code. The objective is to determine the frequency at which a specific word appears in the provided paragraph

function processWords(){ text = document.getElementById("inputText").value; text = text.replace(/(^\s*)|(\s*$)/gi,""); text = text.replace(/[ ]{2,}/gi," "); text = text.replace(/\n /,"&bso ...

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...