Typescript: Defining the correct return type for resolved parameters in promises

Exploring the world of TypeScript, I recently attempted to convert some basic JavaScript promise samples into TypeScript promises. While working on this conversion process, I encountered an issue that has left me puzzled and unable to find a solution even after searching online.

Situation: I have a function that returns a Promise which resolves to a number upon execution. Additionally, I wanted to test various then scenarios with this sample as well.

Below is the code snippet for reference:

function test_promise(): Promise<number>{
    return new Promise((resolve, reject) :number => {
        let result:number = 10;
        resolve(result);
    }).then(result => {            // first then
        console.log("Result: " + (typeof result)); // Result: number
        return result * 2; //
    }).then(result => {            // second then
        return result * 2;
    }).then(result => {            // third then
        return result * 2;
    });
}

I have included two screenshots below for better understanding.

Screenshot 1:

https://i.sstatic.net/S795t.png

Screenshot 2

https://i.sstatic.net/VZK2v.png

Currently, there are a couple of aspects that remain unclear to me:

  1. In screenshot 1, the hint item does not indicate that the typeof result is number, yet when printed using console.log, it shows as a number. What could be causing this discrepancy?
  2. If the console displays the type as number, why does it prevent me from performing multiplication operations on it?

What modifications should I make in order to get this sample functioning correctly?

I would appreciate any insights or guidance you can provide regarding this issue. Thank you.

Best regards,

Answer №1

To solve this problem, make sure to specify the type of value for the initial Promise object you create by including <number> right after new Promise, like this:

    /* Add <number> after new Promise */
    return new Promise<number>((resolve, reject) => {
        let result:number = 10;
        resolve(result);
    }).then(result => {            // first then
        console.log("Result: " + (typeof result)); // Result: number
        return result * 2; //
    }).then(result => {            // second then
        return result * 2;
    }).then(result => {            // third then
        return result * 2;
    });

This step will notify Typescript about the value type of the initial promise, enabling subsequent promises in the sequence to infer their value types accordingly.

By following these instructions, your issue should be resolved. For more details on Generics in Typescript, refer to this resource. Hope this explanation helps!

Answer №2

Review the line below:

return new Promise((resolve, reject) :number => {

In this context, using : number implies that the function is expected to return a number, which is incorrect! The new Promise function actually returns a Promise, so there is no need to specify the return type.

Perhaps what you intended to convey is that the type handled by Promise should be a number. This can be achieved by specifying it within angular brackets:

return new Promise<number>((resolve, reject) => {

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

Insert an HTML tag into JSLint

Is there a way to include an HTML tag in JSLint's list of recognized tags? I'm encountering some errors with the following message: JSLint: Unrecognized tag 'foo'. How can I make the foo tag recognized by JSLint as a valid HTML tag? ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Tips and Tricks for Managing an Extensive Array of AJAX Requests (Exceeding 1000)

My application is retrieving a User's Google Contacts from the Google Contacts API on the front end, resulting in a variable number of JSON objects, usually ranging between 1 to 2000. Upon receiving these objects, the app goes through each one, reform ...

Transform an array from two dimensions to one dimension, while applying specific exceptions

Hello everyone, I'm revisiting a question from before that hasn't been resolved yet. I have a simple requirement - I need a code that will convert my 2D array into a 1D array under one condition. A[0,2,3,7,0,0,5,3][0,2,2,4,0,0,3,0] The desired ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

Angular - The differ is unable to find support for the object 'Item One' which is of type 'string'. NgFor is only able to bind to Iterables like Arrays and not individual objects

Many questions on StackOverflow share similarities with this one, but I have not been able to find a solution that fits my issue. My code functions correctly when attempting to populate items in a "Select" control. It successfully retrieves data if the it ...

I am unable to utilize third-party components within my Nuxt.js/vue.js project

I am attempting to use a library for my Nuxt project, following the guidelines laid out in the documentation available here: getting-started Despite following the instructions provided, I keep encountering errors such as "Unknown custom element: - did you ...

execute a function upon selecting a radio button

Below is the HTML code that includes two radio buttons. The default checked button is the "lease" option. <input id="quotation_request_payment_option_lease" class="choose_payment_option" name="quotation_request[payment_option]" type ...

Troubleshooting: Instagram API JavaScript Example Showing Errors

I'm currently working on integrating a photo feed from my Instagram account by following this tutorial: Below is the snippet of my HTML code with the addition of instafeed.min.js: <!DOCTYPE <!DOCTYPE html> <html> <head> < ...

Acquire XML documentation for overloaded functions in Typescript

Is it possible for an overloaded function in a subclass to automatically inherit the XML documentation from its base class? When hovering over myFunc I want to be able to see the documentation from the base class when I hover over myFunc, rather than ju ...

Typescript does not support index signatures with bracket property accessor when importing using the `import * as`

Currently learning typescript and in the process of converting a large program from javascript. While fixing errors and adding types, I'm stuck on this one particular issue. Here's myModule.ts: export const foo = { ... } export const bar = { .. ...

Can HTML variables be accessed in lines of code before they are declared in HTML?

In line 1 of my code, I am trying to access the rowData variable which is declared in the second HTML line. However, I keep getting the error message "Property 'rowData' does not exist on type 'AppComponent'" for that line. Strangely, t ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...

Combining various Google calendar feeds into a single JSON object using JavaScript

I'm currently in the process of integrating JSON feeds from multiple Google calendars to organize upcoming events and showcase the next X number of events in an "Upcoming Events" list. While I initially achieved this using Yahoo! Pipes, I aim to elim ...

Creating a personalized instance function in Angular's $resource

When working with AngularJS, all actions for a $resource are added as $customAction methods to the Resource. This allows me to easily invoke them as methods on resource instances. For example: var User = $resource('/user/:userId', {userId:' ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

The expected functionality of sending files via ajax is not happening as anticipated

I am having issues with passing file data along with other inputs to my ajax function. Despite my best efforts, the server is not receiving the files. I'm fairly new to using ajax and Jquery. Below is the code snippet of what I have attempted so far. ...

Unable to combine mui theme with emotion css prop

I recently made the switch from overwriting styles in my styles.css file with !important to using emotion css prop for implementing a dark theme in my web app. Below is the code snippet from App.tsx where I define my theme and utilize ThemeProvider: const ...

The Material UI dialog is causing issues for CKEditor 4

In the midst of my React project, I have incorporated CKEditor 4 into a Material UI dialog. However, when attempting to utilize advanced features like Math, I encounter an issue where I am unable to input any text into input or textarea fields. Despite sea ...

"Challenges Encountered When Using Vue.js to Handle Image Paths Containing Variables

I've come across a challenge while trying to create a dynamic image path based on the props passed in Vue.js. Despite my efforts, such as using variables for the images, CSS variables, and moving the images to the src folder (although this caused issu ...