Redundant function implementation detected in Typescript

Currently, I am developing an adapter for the HttpClient in Angular that requires two different get functions - one for returning a Blob and another for returning a generic. However, when I try to execute this implementation, I encounter the following error:

Error TS2393: Duplicate function implementation.

  get<T>(url: string, options?: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    context?: HttpContext;
    observe?: 'body';
    params?: HttpParams | {
      [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
  }): Observable<T> {
    return this.handleRequest(this.http.get<T>(url, options));
  }

  get(url: string, options: {
    headers?: HttpHeaders | {
      [header: string]: string | string[];
    };
    observe: 'response';
    context?: HttpContext;
    params?: HttpParams | {
      [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
    };
    reportProgress?: boolean;
    responseType: 'blob';
    withCredentials?: boolean;
  }): Observable<HttpResponse<Blob>> {
    return this.handleRequest(this.http.get(url, options));
  }

It's perplexing to me that I'm receiving an error considering that the actual implementation of these get functions in the HttpClient class is very similar.

Answer №1

In JavaScript, it is not possible to have two functions with the same name within the same scope. Instead, you should create a single function that can determine which arguments are being passed and execute the appropriate functionality. With TypeScript, you can define multiple function signatures to ensure correct typing. For example:

get<T>(url: string, observe: 'body'): Observable<T>;
get(url: string, observe: 'response'): Observable<HttpResponse<Blob>>;
get(url: string, observe: 'body' | 'response') {
  if (observe === 'body') {
    // ... implementation
  } else {
    // ... implementation
  }
}

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 the reason for the date locale 'en-CA' displaying the format M/d/yyyy instead of yyyy-MM-dd?

My JavaScript code is set up to show the current date in en-CA format. date = new Date(); console.log(date.toLocaleDateString('en-CA')); In the past, dates in the en-CA locale were displayed as yyyy-MM-dd (2023-02-24). However, suddenly today ...

The functionality of Javascript is only accessible once you open the developer tools in Chrome

I am encountering a similar issue to the one discussed here: Why does JavaScript only work after opening developer tools in IE once? However, in my case, the problem arises in Chrome 44. The JavaScript code, particularly involving XHR and setInterval, f ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

Utilizing Audio Record Feature with a pair of buttons - one for initiating recording and the other for concluding recording

I'm new to Vue.js and trying to create a simple audio recorder that starts recording on click of a button and stops when another button is clicked. The goal is to display the audio file in the template and save it locally as a blob. Here is the templ ...

Using Vue.js to dynamically render content in the DOM based on file extensions

Previously, I used Vue.js to load various text and media data from an object into the DOM. Sometimes it was images, other times videos. To handle this, I came up with the following solution: <img id="example-image" :src="item.media" :alt="item.image + ...

Transmit information to a webpage using jQuery AJAX and the .data() function as you navigate to the page

<script> function sendUserData(username){ $.post("userprofile.php", { username:username } ); document.location.href="userprofile.php"; } $(document).on('click','#userprofile',function(){ var username=$(this).data('id4&apo ...

Troubleshooting HTTP requests in Angular JS when dealing with nested scopes

This particular question is derived from a previous answer found at this link. In my current scenario, I am attempting to initiate an http request where one of the data values that needs to be sent is represented in the view as {{selectedCountry.shippin ...

The potential dangers associated with enabling the Set-ExecutionPolicy command with the RemoteSigned value

When installing certain packages like typescript through NPM, there are instances where you need to run the command: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned In PowerShell, if you try to change this policy, a warning message indicates that: Ch ...

Creating a clickable div using JavaScript: A step-by-step guide

paramToExternalFile = 'all'; var div = document.createElement('div'); div.style.background = '#D8D8D8'; div.innerHTML = '<a href=' + xml_list_externalFile_SNS1 + paramToExternalFile + '/' + letters + &a ...

When using the .append method in jQuery, the JSON array only displays the last value of the array when iterating through it with

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Displaying Array Data in Table Using Javascript</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">& ...

Attempting to create a school project involving pizza, but encountering some technical difficulties

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>pizza ...

Creating Versatile Functions for HttpClient Wrapping

Scenario: In my set of services, I find myself repeatedly writing code for data calls which results in a lot of duplicated code. To streamline the process and reduce redundancy, I am looking to implement a wrapper function: All these functions essentiall ...

Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

Removing information from firebase using a distinct identifier for targeting

My goal is to implement a delete functionality on my website by adding delete buttons next to each data entry displayed in the "#table_body". These buttons are dynamically created using JavaScript. The challenge I'm facing is how to remove the data ba ...

Leveraging jquery within an XML document in a SAPUI5 fragment

I'm experiencing a minor issue with my app. I have an Image property that has an empty background, and I want to add a class to it when clicked. However, my controller is unable to detect classes or IDs of properties in the view.xml document. Is there ...

If I include beforeRouteEnter in one component, the this.$route property may become undefined in another component

I seem to be encountering an issue. After implementing a beforeRouteEnter method in one component, I am unable to access this.$route in another component. Here is the structure of my app: <div id="app"> <settings-modal></settings-modal ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

Choosing the element g within the SVG element using Selenium

I'm new to using selenium and I've hit a roadblock that I could really use some expert advice on. Here is the HTML code I'm working with: <div id='d3_tree'> <svg> <g transform="translate(20,50)> ...