Mapping a list containing various types of objects that share similar attributes

Currently, I am attempting to map a list containing objects with the same attribute but different types:

doStuff(list: Array<FilterStatus> | Array<CaseDefinition>){
  list = list.map(value => ({...value, checked: true}));
}

I am encountering a TypeScript error, which is expected due to the varying types within the list. However, I am unsure of how to resolve this issue. Any suggestions or tips would be greatly appreciated.

: Cannot invoke an expression whose type lacks a call signature. Type '((callbackfn: (value: FilterStatus, index: number, array: FilterStatus[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: CaseDefinition, index: number, array: CaseDefinition[]) => U, thisArg?: any) => U[])' has no compatible call signatures.

For reference, here is a reproducible example:

Reproducible Example in TypeScript Playground

Answer №1

It is recommended to use

Array<FilterStatus | CaseDefinition>

over

Array<FilterStatus> | Array<CaseDefinition>

The first option creates an array containing either FilterStatus or CaseDefinition, while the second one creates two separate arrays for FilterStatus and CaseDefinition

Here's a complete example:

export interface FilterStatus  {
    name: string;
    checked: boolean;
}

export interface CaseDefinition {
    title: string;
    checked: boolean;
}

const aList: FilterStatus[] = [{name: 'name', checked: false}];
const bList: CaseDefinition[] = [{title: 'title', checked: false}];


function doStuff(list: Array<FilterStatus | CaseDefinition >) {
    list = list.map(value => ({ ...value, checked: 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

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

What is the best way to retrieve app.state in a Remix project when running a Cypress test?

One way Cypress can expose an app's state to the test runner is by using the following approach in React: class MyComponent extends React.Component { constructor (props) { super(props) // only expose the app during E2E tests if (window.C ...

Implement FieldResolver in TypeGraphQL for an array of objects

My current dilemma revolves around a specific issue related to the definition of my Cart type, which is structured as follows: @ObjectType() export class Cart { @Field(() => ID) id: string; @Field((_type) => String) ownerId: String ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

The type 'Readonly<Ref<Readonly<any>>>' does not have the property 'forEach' available

Having an issue with state management in Vue3 (Pinia) using the Composition API. I successfully retrieved an array called countryCodes and now I want to copy all items from this array into another array called countries defined in the state. However, whe ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

What method can I utilize to display a value that deviates from the one stored in the backend using Record?

Here is the HTML snippet that I am working with: <drop-down-list [name]="MeetingTool.Type" [options]="options$" [isRequired]="false" class="input-width" ...

Removing a value from a JavaScript object

Looking to delete a specific value from an object with multiple values? This is how my object is structured: { 'how can i change my password?': [ 'how can I change my password?', 'how may I change my password?', ...

In JavaScript, the act of shuffling an array will produce consistent results

I have created a random array generator by shuffling an initial array multiple times. SHUFFLE FUNCTION const shuffle =(array) => { let currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Ma ...

NestJS - The GraphQL schema was expected to be defined, but was found to be

I've been working on setting up a small GraphQL API using NestJS 8. I made sure to install all the required dependencies as per the documentation. However, upon starting the server, I am encountering this error: [Nest] 22727 - 10/30/2021, 10:11:10 AM ...

Using a string containing several nested keys to search through an array for matching values in PHP

Is there a way in PHP to use a multiple child 'key' as a 'lookup' to retrieve an object from various associative arrays? For example: $lookup_key = "['objects'][0]['object2']"; // This key will be used to retrieve ...

Launching Node Application

While working with NestJS and IIS, I encountered an issue when deploying my 'dist' folder on the server using IISNode. The error message 'module not found @nestjs/core' prompted me to install the entire 'package.json' files (n ...

What is the best way to extract values based on a key

export class Installment { constructor( public isResurring: boolean, public isInstallment: boolean, public price: string, public sku: string ) { } this.keys = Object.keys(this.paymentPlans); for(let key of this. ...

Converting a Powershell array into an HTML format

I have three arrays that I need to display on an HTML page: foreach($item in $array1){ // write array data to HTML } foreach($element in $array2){ // write array data to HTML } foreach($value in $array3){ // write array data to HTML } What is the ...

The Angular4 Grunt build task is encountering an issue where it cannot locate the module '@angular/core/testing'

I've been working on setting up a Grunt build task for my Angular 4 project, but I'm encountering some module load errors when trying to run the tasks. Here are the steps I have taken so far: 1. Visited https://angular.io/guide/quickstart and f ...

Tips for concealing backend data in Angular2 under the conditions where the name is designated as anonymous and the nested array is empty

I'm dealing with an array of data fetched from the backend and I need to meet the following requirements: If the user's name, "from_user_name", is Anonymus, then the contents must be hidden. Hide the messages if the array is empty. Can someone ...

How to Launch Angular 4 App on AWS: Step-by-Step Guide

I need advice on how to deploy my Angular 4 application on either Amazon Web Services or Godaddy Hosting. Can anyone offer any guidance or tips? Any assistance would be greatly appreciated. Thank you in advance. ...

Can template literal types be utilized to verify if one numeric value is greater than another?

I am attempting to define the Record for migration functions, which use the direction of the migration as the key: v${number}-v${number}, Considering that these migrations are all UP, they need to be validated as v${first-number}-v${first-number + 1} and ...

What are the steps for integrating Angular Material into an existing project?

I have recently set up an Angular 2 project. Attempting to integrate Angular Material into my existing project, I followed the steps outlined in the official documentation by running the npm command: npm install --save @angular/material @angular/cdk How ...

Identify alterations in a variable and trigger an event

I have a button labeled 'Refresh Data' that triggers the refreshBatchData() function: refreshBatchData(){ this.homeService.refreshData().subscribe(data => { this.batchSpotData = data; }) } After receiving data in batchSpo ...