Invoking functions using union types in Angular TypeScript

I have a challenge where I need to pass an Array<number|string> to a function that accepts Array<number|string> and returns either an Array<number> or an Array<string>.

Unfortunately, the method overloading doesn't seem to be working as expected. What could be the issue preventing it from functioning correctly?


user.model.ts

export interface User {
  text: Array<string | number>;
}

user.service.ts

import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class UserService {
  public getText(text: Array<string>): Array<string>;
  public getText(text: Array<number>): Array<number>;
  public getText(text: Array<string | number>): Array<string | number> {
    return text;
  }
}

app.component.ts

export class AppComponent implements OnInit {
  title = "CodeSandbox";

  constructor(private userService: UserService) {}

  ngOnInit() {
    const user: User = {
      text: ["string"]
    };

    this.userService.getText(user.text);
  }
}

Error:

No overload matches this call.
  Overload 1 of 2, '(text: string[]): string[]', gave the following error.
    Argument of type '(string | number)[]' is not assignable to parameter of type 'string[]'.
      Type 'string | number' is not assignable to type 'string'.
        Type 'number' is not assignable to type 'string'.
  Overload 2 of 2, '(text: number[]): number[]', gave the following error.
    Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'.
      Type 'string | number' is not not assignable to type 'number'.
        Type 'string' is not assignable to type 'number'.ts(2769)

Repo: https://codesandbox.io/s/eloquent-resonance-ilfvm?file=/src/app/app.component.ts

Answer №1

Here is a possible solution:

export class TextService {
  public processText(text: Array<string>): Array<string>;
  public processText(text: Array<number>): Array<number>;
  public processText(text: Array<string | number>): Array<string | number>;
  public processText(text: Array<string | number>): Array<string | number> {
    return text;
  }
}

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

Reorganize mat-table rows using Angular Material's drag-and-drop feature

One of the new features that came with Angular 7 is the powerful DragDropModule: https://material.angular.io/cdk/drag-drop/examples The documentation covers rearranging items in lists and transferring them between different lists, but it doesn't ment ...

The Angular 4 application is unable to proceed with the request due to lack of authorization

Hello, I am encountering an issue specifically when making a post request rather than a get request. The authorization for this particular request has been denied. Interestingly, this function works perfectly fine with my WPF APP and even on Postman. B ...

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...

I am having trouble reaching the _groups attribute in angular/d3js

I am encountering an issue when trying to access the "_groups" property in my code: function getMouseDate(scale){ var groupElement = d3.select("#group")._groups[0][0] var xCoordinate = scale.invert(d3.mouse(groupElement)[0]); co ...

Have I repeated myself in defining my class properties?

Currently, I'm enhancing my understanding of Typescript with the development of a discord.js bot. However, I have come across a piece of code and I am uncertain about its redundancy: import Discord from 'discord.js'; export default class B ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Creating a custom string subtype in TypeScript

I am currently working on developing a game called Risk using TypeScript and React hooks. This game is played on a map, so my first step was to design a MapEditor. The state of the Map Editor is as follows: export interface IMapEditorState { mousePos: ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

Determine if the grid is accurately sorted in sequence using Cypress

I am currently working on sorting images based on their order, with the options for new and old. The [data-cy="list-file"] wraps all the images, while [data-cy=fileCard-list] represents each individual image. After selecting the 'old' b ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

What is the most efficient method for incorporating React into Wordpress while using Typescript?

Is it possible for me to utilize the React / React-Dom scripts that Wordpress has enqueued in my bundled javascript, while still being able to use the -dev installed React for development purposes? The javascript files are designed for a WordPress plugin ...

Issues arise when trying to implement Angular SCSS with ngx-datatable

I am encountering an issue with my SCSS. It seems that the CSS command from the SCSS file below is not being utilized. This particular SCSS file is generated with the component. Interestingly, when I place the code in the styles.scss file included in the ...

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

Numerous modules accessible via Angular-cli

I'm currently working on an application using the angular-cli interface. However, I have realized that there are no commands available such as: ng generate module featureModule As a result, I am forced to create modules manually. Can someone advise ...

I am having trouble retrieving child interface data from API using Angular. Can someone help me figure out what I am doing

Recently started with Angular 7 and could use some guidance. I have a JSON stream that appears as follows: { "Id": 25, "Name": "XYZ Corp", "CompanyAddresses": [ { "Id": 39, "CompanyId": 25, "Address1 ...

Is transitioning from AngularJS to Angular truly imperative?

We currently have a project built with AngularJS, but its support is ending and there are potential security vulnerabilities (CVEs) present. Do we need to transition to a different framework? Our project primarily involves front end development with data b ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...