What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service:

class SettingsService implements ISettingsService {

    public info = {};
    public backupInfo = {};
    public userConfig = {};
    public isLoaded = false;

    constructor(
        private $http: ng.IHttpService,
        private $q: ng.IQService
        ) {

    }

    static $inject = [
        '$http',
        '$q'
    ];

    save = ():ng.IHttpPromise<> => {
        var defer = this.$q.defer();
        if (angular.equals(this.info, this.backupInfo)) {
            return defer.resolve();
        } else {
            this.$http({
                data: {
                    infoJSON: JSON.stringify(this.info),
                    userConfigJSON: JSON.stringify(this.userConfig)
                },
                url: '/api/Settings/Save',
                method: "POST"
            })
                .then(function (data) {
                    this.backupInfo = angular.copy(this.info);
                    this.userConfigBackup = angular.copy(this.userConfig)
                    return defer.resolve();
                });
        }
        return defer.promise;
    };

}

In addition to the service, I defined an interface as well:

interface ISettingsService {
     save(): ng.IHttpPromise<>;
}

Unexpectedly, there's an error occurring in the code:

Error   3   Cannot convert 'void' to 'ng.IHttpPromise<any>'.    

Error   4   Cannot convert 'ng.IPromise<{}>' to 'ng.IHttpPromise<any>':
    Type 'ng.IPromise<{}>' does not have the property 'success' as expected in type 'ng.IHttpPromise<any>'.  

Answer №1

Utilize

ng.IPromise<void>

You can also have it infer the type for you if you omit declaring a return type and do not utilize that interface.

In addition, there is no need for a return statement in this section:

return defer.resolve();

Simply include:

defer.resolve();

Answer №2

When faced with this issue, I encountered a problem where I could not use ng.IPromise<void> because the declarations for ng.IHttpPromise<> required me to return an object.

For instance:

public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<void> => {
    var data = {
        jobNumber: jobNumber,
        subject: technicianNote.subject,
        details: technicianNote.details
    };
    return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}

resulted in an error stating that

Type IHttpPromise<{}> is not assignable to IPromise<void>
.

To work around this issue, I changed it to return ng.IPromise<any>. While not perfect, it was the most suitable solution I could find without having to modify angular.d.ts.

Modified Code:

public saveTechnicianNote = (jobNumber: string, technicianNote: Model.TechnicianNote): ng.IPromise<any> => {
    var data = {
        jobNumber: jobNumber,
        subject: technicianNote.subject,
        details: technicianNote.details
    };
    return this.$http.post(this.urlFactory.saveTechnicianNote, data);
}

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 to Retrieve JSON Object Using Dynamically Generated String in Angular

Creating a controller in Angular involves retrieving URL parts and parameters using $statePrams. The $http service is then called to retrieve data from a JSON file. Once the data is received, the content of a specific object element - determined by $state ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

The NgZone reference error caused the prerendering to fail

I am facing challenges with the implementation of NgZones. Despite defining NgZone, I keep encountering this error: "NodeInvocationException: Prerendering failed because of error: ReferenceError: NgZone is not defined" Below is my app.error-handle.ts file ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

Disabling cache in AngularJS is being overridden by Chrome's cache

I'm currently encountering an interesting caching issue while using Chrome. My angularjs service looks like this: var url = '/api/acts/' + accountId + '/policy/?filter=NEW_POLICY'; return $http({ ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

Retrieving form data from within the resource error callback scope

For my client-side validation on submit, I am calling a resource if the form is valid. On success, everything works fine. However, when encountering an error handler, I also perform server-side validation on my data transfer object bean which contains Hibe ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

What is the syntax for creating a function with parameters of type `any` or `void` in TypeScript?

How can I create a function in typescript that accepts either something or nothing as input? I attempted the following: interface TestFn { (input: any | void): string } const operation: TestFn = (input) => 'result'; operation('some ...

Managing the outcome of numerous asynchronous calls before accessing the database post-result collection

Hey everyone, I'm just getting started with node.js and I'm working on the following tasks: Calling the AWS API to create Cognito users by passing data. After all requests are completed, inserting all the records into the database. In my code, ...

Angular.js not capturing x-access-token

When utilizing the POSTMAN Chrome extension to make an API call api.get('/me', function(req, res) { res.json(req.decoded); }); return api; By using x-access-token as a header with a valid token value, I receive a successful response. Howe ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

How can we leverage RxJS combineLatest for observable filtering?

I'm exploring the possibility of utilizing combineLatest in an Angular service to eliminate the need for the activeFiler$ switch block (The service should achieve the same functionality). Currently, this is the structure of the component design (stack ...

ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions? app.component.html: <label> Nam ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

What are the steps to utilize the Angular package within NodeJS and Express?

After installing the Angular package through npm install for my Express project, I am feeling a bit lost on how to actually use it. Can someone explain how to properly implement Angular after installing it this way? Alternatively, is the only way to util ...

Refreshing the view upon receiving data from an API in AngularJS

Hey there, I've encountered a small issue. Recently, I created a mini web application that utilizes the omdb api. The problem lies in the fact that when I input the movie I'm searching for and hit the search button, the view is supposed to transi ...