Using Promise<void> instead of Promise<any> is the preferred approach

Working with AngularJS, I have created several asynchronous functions that all use the same signature, which is app.Domain.GenericModel.EntityBase (my generic model). Here is an example:

get(resource: string): ng.IPromise<app.Domain.GenericModel.EntityBase[]> {
            var self = this;
            var deferred = self.qService.defer();
            self.httpService.get(resource).then(function (result: any) {
                deferred.resolve(result.data);
            }, function (errors) {
                self.exception = new app.Exceptions.Model.Exception(errors.status, errors.statusText);
                deferred.reject(self.exception);
            });

            return deferred.promise;
        }

When attempting to call similar services with chained promises, I encountered the following error: "Type IPromise is not assignable to type IPromise, Type EntityBase is not assignable to type void"

   var self = this; 
    var promise = self.$q.when();
    promise = promise.then(() => {
                                            return self.EcritureService.get(critureToSave);
                                        }).then((compte: EntityBase) => {
                                            return self.CompteService.getSingle(Number(data.compte));
                                        }).then((EntityBase) => {
                                            currentAccount.montantCpt = currentAccount.montantCpt + montant;
                                            return self.CompteService.update(currentAccount:EntityBase);
                                        });

I have researched extensively for a solution to this issue and have only come across a method to convert my functions' returns to the common pattern "IPromise" through Type assertion, which seems to rely on some trickery or deception by the compiler. If anyone has a better understanding of this technique, please share it regardless of its efficiency.

Answer №1

By default, the variable promise in your scenario will be of type ng.IPromise<void> as that is what $q.when() will return.
Assigning an ng.IPromise<EntityBase> object to a variable of type ng.IPromise<void> is not allowed.
Depending on your desired outcome, there are various approaches you could take.

One option is to use a different variable to store your subsequent promise:

let anotherPromise = promise.then(() => { ...

You can also explicitly specify the type of your variable as ng.IPromise<any> initially:

let promise: ng.IPromise<any> = self.$q.when();
let promise = promise.then(() => { ...

Alternatively, make sure your promise chain ultimately returns a promise of void:

promise = promise.then(() => {... your chain ...}).then(() => { });

There may be other solutions available as well, but hopefully this gives you some guidance.

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

Combining Gulp and Bower seamlessly with Django to enhance AngularJS functionality

I'm a beginner in Django and I'm trying to set up an AngularJS template with Django. The AngularJS template I am using has gulp configuration. Can someone please guide me on how to configure gulp with Django to run the AngularJS template? Any sug ...

What is the best way to save time in a MySQL database?

HTML <input type="date" ng-model="bookdate" required> <input type="time" ng-model="booktime"> Controller $scope.insertData=function(){ bookdate=$scope.bookdate; booktime=$scope.booktime; $http.post("url", { ...

Does this fall under the category of accepted practices for employing an effect in Angular?

I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal ...

Calculate the total of an array with the help of the angular forEach function

function dialogController(generate, $scope) { $scope.profiles = generate.get_keys('::role'); $scope.content = {}; $scope.options = []; $scope.servers = {}; $scope.subs = {}; $scope.discountList = {}; $sco ...

Using Angular.js to make an Ajax request with a callback function within an ng-repeat element

At the moment, I am delving into Angular.js coding and working on a project that involves loading data through Ajax queries. In simple terms, my data is organized in three levels: -- Skills --- Indicators ---- Results My initial request focuses on tra ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

Interacting with the Dropdown feature on the page causes the body of the page to shift

I am encountering an issue with 2 dropdowns in Datatables used to filter content. The problem arises when a dropdown is positioned on the right side of the page, causing a shift to the left by approximately 10px. Conversely, if the dropdown is placed on th ...

AngularJS struggles to set the default value for linked dropdown menus

I've successfully created a chained dropdown, but I'm struggling to set initial values for them. Here's what I have so far: <select ng-model="check" ng-options="check.name for check in checks"></select> <select ...

The third column sort click in KendoUI Grid causes the data.sort array in the DataSource parametermap to become undefined

I am currently working with a datagrid configuration that looks like this: <script> angular.module("KendoDemos", [ "kendo.directives" ]); function MyCtrl($scope) { $scope.mainGridOptions = { dataSource: { transport: { ...

Submitting alterations to the server with AngularJS: Utilizing $resource for POST requests

I'm having issues with a particular AngularJS problem. On the server, I have a model stored in a .json file: { feedback: [] } The goal is to collect user input from a form and add it to the feedback array as individual javascript objects. I at ...

Unable to access component properties through react-redux

Context: A React Native application utilizing Redux for managing complexity. Versions: typescript v3.0.3 react-native v0.56.0 redux v4.0.0 @types/react-redux v6.0.9 @types/redux v3.6.0 Issue: The main JSX component in my app is unable to access proper ...

Tips for assessing the prop that is being passed to a styled component with React and TypeScript

I am trying to apply a background color to a styled component div only if the state "active" is true. This is how I am currently attempting to do it: function Main() { const [active, setActive] = useState(false); return ( <ChildCompone ...

The function Array.foreach is not available for type any[]

I'm encountering an issue where when I attempt to use the ".forEach" method for an array, an error message stating that the property 'forEach' does not exist on type 'any[]' is displayed. What steps can I take to resolve this probl ...

Steps to prevent uib-timepicker from automatically adjusting time based on the Browser Timezone

Currently in my database, timestamps are stored in UTC format. On the frontend, I am implementing uib-timepicker for time editing and updating purposes. However, I do not want uib-timepicker to automatically convert the time from the server's timezone ...

Error message: Typescript class unable to access methods because of undefined properties (TypeError: Cannot read properties of undefined (reading 'method_name'))

During the compilation process, everything goes smoothly with no errors. However, when I try to call the method in the controller, an error occurs. It seems that some class methods are missing during the compilation phase. If you require more information ...

What is the best way to asynchronously refresh Angular 2 (or 4) PrimeNg Charts?

Issue: How can PrimeNg Charts be updated asynchronously? Situation: I have a dropdown menu that should trigger a chart refresh based on the user's selection. I believed I had the solution figured out, understanding Angular change detection and reali ...

Creating a unique theme export from a custom UI library with Material-UI

Currently, I am in the process of developing a unique UI library at my workplace which utilizes Material-UI. This UI library features a custom theme where I have integrated custom company colors into the palette object. While these custom colors work perfe ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

AngularJS: Initiate a Bootstrap modal upon webpage loading

As I work on designing a web application using AngularJS, I aim to implement the launching of a bootstrap modal upon page load through AngularJS. Here is the structure of my modal: <div class="modal hide fade" id="myModal"> <div class="moda ...