Unraveling a commitment within a JSDoc type using ReturnType: Tips and Tricks

Below is the code snippet I need help with:

const foo = async () => {
  return 1
}

I am looking to assign a type to a variable that matches the ReturnType of the function, but after the promise has been resolved.

When attempting the following:

/** @type {ReturnType<foo>} */
let bar

The output is Promise<number>, but I actually want it to be number.

Can this desired result be achieved using JSDoc? If so, how can it be done?

Answer №1

Implement the Awaited<T> type for best results.

/** @type {Awaited<ReturnType<exampleFunc>>} */
let variable

Answer №2

I am having trouble grasping the main issue and the reason behind this implementation method. By using async before a function, it will generate a promise. When you call this method, it will return a promise (Promise<number>).

METHOD-1

You can easily specify the return type of this function as shown below:

/**
 * Return a promise
 * @return {Promise<number>} A promise of type number.
 */
const foo = async () => {
  return 1
}

Similarly, you can do the same with your variable like so:

/** @type {Promise<number>} */
let bar = foo();

METHOD-2 - If you wish to convert this to a data type of number, there is no direct way but we can certainly achieve it by adding an extra function here. Simply handle the promise using the then method and pass the resolved value for assignment in the new function.

In this case, your function will remain unchanged as it will always return a promise.

/**
 * Return a promise
 * @return {Promise<number>} A promise of type number.
 */
const foo = async () => {
  return 1
}

/** @type {number} */
let x = -Infinity;
function assignVariable(myValue) {
  x = myValue;
  console.log(x);
}

foo().then(value => {
  assignVariable(value);
});

Here is the snippet that works as expected:

const foo = async () => {
  return 10;
};

let x = -1;
function assignVariable(myValue) {
  x = myValue;
  console.log(x)
}

foo().then(value => {
  assignVariable(value);
});

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

Tips for using useState with dependencies on custom objects such as { filter[], sort[] }:

I am trying to use the useState Hook with a custom object that contains two arrays as shown below const [initConfig, setInitConfig] = useState<>({filter:[], sort:[]}); However, I am unsure of how to declare inside the angle brackets. The filter arr ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Tips for integrating Material-Ui Autocomplete with Formik's Field component to create Multi-Select check boxes

Trying to integrate Formik's Field component with Material-Ui Autocomplete for multiple values that include checkboxes has been challenging. Whenever a value is selected from the dropdown list, the popup closes and needs to be reopened for the next se ...

modification of the tooltip's background shade on Google Maps

Currently, I am using Google Chart to display data for different countries. When hovering over these countries, a tooltip is displayed which fetches data from the backend. However, I would like to customize the background color of this tooltip as it is cur ...

Disregard the triggering of a parent component's event when clicking on the slot child component in Vue

Is there a way to prevent the emit from the click on the DataTable row if I have also clicked on the Button inside the slot? I've seen this done with native components using @click.prevent, but I'm not sure how to achieve the same functionality w ...

Guide on how to swap a string with a component in Vue

I have a string that contains placeholders ### and I want to replace them with values from an array. I created a component, but I'm not sure how to incorporate it into the string since the number of placeholders can vary. For instance, if there are 2 ...

Struggling with implementing an EventEmitter in Angular2?

I am facing an issue with handling an EventEmitter in my child component, which is a list of devices. The parent component displays details of the selected device and I want to be able to change the selected device when needed. However, I keep getting an e ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...

Establishing the initial value of a <select> element

My webpage features a table that displays the details of past order history, with columns for Order, Date, and Review. For the Review column, I am seeking to add a select dropdown with various options. Upon the initial page load, I would like the select d ...

What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon amon ...

Utilizing Firebase in place of .json files for the AngularJS Phonecat application

I am currently exploring firebase and attempting to retrieve data using this service from firebase instead of json files. However, I have encountered some challenges in getting it to function properly. This is inspired by the angularjs phonecat example .f ...

GridView and UpdatePanel - preserving the same perspective

Assistance needed for implementing an UpdatePanel. Here is the grid structure: <asp:UpdatePanel ID="UpdatePanel1" runat="server" EnableViewState="false" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger C ...

Leverage the template pattern in React and react-hook-form to access a parent form property efficiently

In an effort to increase reusability, I developed a base generic form component that could be utilized in other child form components. The setup involves two main files: BaseForm.tsx import { useForm, FormProvider } from "react-hook-form" expor ...

What is the reason that the insertBefore() method fails to properly extract an element from the friendly iframe in IE7?

I'm looking to extract an element from the DOM tree of an iframe and transfer it to the DOM tree of the parent document. Although this process is successful with most modern browsers, it encounters an issue with IE7, generating an Error: Invalid argu ...

The CycleDOM conundrum with conditional rendering

Having a problem with conditional rendering. Check out my flawless view: function todoItem(todo) { return li('.list-item',[ todo.editing ? input('.todo-edit', {type: 'text', value: todo.text, autofocus: true, attributes ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

Troubleshooting in Angular 7: When Auth0 parseHash response is returning null

Having trouble with Auth0. Upon sign-out and browser refresh, my application is unexpectedly triggering the login event again and encountering user profile issues. The root of the problem seems to lie in the parseHash method within the authentication serv ...

What is the best approach for integrating HTML and JavaScript code into Flutter mobile platforms?

For the past 4 months, I've been immersing myself in Flutter without any prior experience in Javascript. My goal is to utilize the Soundcloud HTTP API to create a user-interactive app. However, I've hit a roadblock when it comes to integrating JS ...