Tips on assigning array union as the return type of a function

I am working with a function parameter that accepts an array union, like this: (ClassA|ClassB)[].
How can I return either ClassA[] or ClassB[] from the function?

When attempting to return type (ClassA|ClassB)[], I encounter the following error:

Assigned expression type (ClassA|ClassB)[] is not compatible with type ClassA[].

classA: ClassA[];
classB: ClassB[];

this.classA = this.function(this.classA, classAObject);
this.classB = this.function(this.classB, classBObject);

function(array: (ClassA|ClassB)[], item: ClassA|ClassB): any {
   // some code...
   return array;
}

Answer №1

collection: ClassA[] | ClassB[]

Please make sure to specify if it is either a collection of ClassA OR a collection of ClassB, not a mix of items that could be either ClassA or ClassB.

Answer №2

Implementing function overloading can help achieve the desired type signature:

class X {
  x() {}
}
class Y {
  y() {}
}

const x = new X();
const y = new Y();

const arrayOfX: X[] = [];
const arrayOfY: Y[] = [];

function performAction(array: X[], item: X): X[];
function performAction(array: Y[], item: Y): Y[];
function performAction(array: X[] | Y[],item: X | Y): X[] | Y[] {
  return array;
}

const resultOfX = performAction(arrayOfX, x);
const resultOfY = performAction(arrayOfY, y);

It can be observed that resultOfX is inferred to be of type X[], and resultOfY as type Y[].

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

How do I make functions from a specific namespace in a handwritten d.ts file accessible at the module root level?

Currently, I am working on a repository that consists entirely of JavaScript code but also includes handwritten type declarations (automerge/index.d.ts). The setup of the codebase includes a Frontend and a Backend, along with a public API that offers some ...

Is it possible to retrieve the selected DataList object in Angular 10?

I encountered an issue while creating an Input field with DataList. My goal was to retrieve the entire object associated with the selected option, but I could only access the selected value. Previous suggestions mentioned that DataList items should be uniq ...

The error message "Theme does not include property 'navHeight'" is indicating that the 'navHeight' property is not defined within the 'Theme' type. This issue occurs when using MUI v5 syntax with Types

When attempting to incorporate MUI with new props declared in the Interface inside the theme.ts file (as suggested by the MUI docs), I encountered the error mentioned above while theme.palette.primary.main does work. Despite trying various solutions like i ...

I encountered an issue while attempting to retrieve data using route parameters. It seems that I am unable to access the 'imagepath' property as it is undefined

Is there a way to access data when the page loads, even if it is initially undefined? I keep getting this error message: "ERROR TypeError: Cannot read properties of undefined (reading 'imagepath')". How can I resolve this issue? import { Compone ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

The useParams() method results in a null value

When attempting to utilize the useParams() hook in nextjs, I am encountering an issue where it returns null despite following the documentation. Here is my current directory structure: pages ├── [gameCode] │ └── index.tsx Within index.tsx ...

Absence of "Go to Definition" option in the VSCode menu

I'm currently working on a Typescript/Javascript project in VSCODE. Previously, I could hover my mouse over a method to see its function definition and use `cmd + click` to go to the definition. However, for some unknown reason, the "Go to Definition" ...

Middleware for Redux in Typescript

Converting a JavaScript-written React app to Typescript has been quite the challenge for me. The error messages are complex and difficult to decipher, especially when trying to create a simple middleware. I've spent about 5 hours trying to solve an er ...

My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it en ...

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...

The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function. interface Request { ids: string[]; resolver: () => void; promise: Promise<unknown> } class Foo { public requests: ...

BehaviorSubject Observable continuously notifies unsubscribed Subscription

Utilizing a service called "settings", initial persisted values are read and provided through an observable named "settings$" to components that subscribe to it. Many components rely on this observable to retrieve the initial values and exchange updated va ...

Leveraging the TypeScript definitions for express-validator

I've been working on converting my code to TypeScript, but I'm running into issues with express-validator definitions. Here's a snippet of my code: ///<reference path='../../../d.ts/node.d.ts' /> ///<reference path=&apos ...

Expanding index signature in an interface

Is there a way to redefine the old index signature when trying to extend an interface with different property types? I am encountering an error when adding new properties that have a different type from the original index signature. interface A { a: num ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...

Unable to initiate ngModelChange event during deep cloning of value

I've been struggling to calculate the sum of row values, with no success. My suspicion is that the issue lies in how I am deep cloning the row values array when creating the row. const gblRowVal1 = new GridRowValues(1, this.color, this.headList ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Mental stability groq fails to provide the requested information

Having difficulty using Groq to fetch data. All other Groq queries work fine, except this one. When manually setting the $slug variable, the data I'm trying to query works with the Sanity Groq VS plugin but returns undefined in my web app. Query: exp ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...