Transforming a "type containing promises as property values" in Typescript into a "type containing resolved promise values as properties"

Can this be achieved in Typescript?

I am looking to transform something like the following:

interface IPromiseObject {
    promiseA: Promise<number>;
    promiseB: Promise<string>;
}

Into this:

interface IResolvedPromiseObject {
    promiseA: number;
    promiseB: string;
}

I aim to resolve an object with promises as values while maintaining type safety. Specifically, I need to convert IPromiseObject into an object with the same keys but resolved values, which can then be used as a return type.

export async function resolveAllObject<IPromiseObject>( promiseObject: IPromiseObject ): Promise<???> {
    const resolvedPromiseObject = {};
    for ( const key in promiseObject ) {
        const value = await promiseObject[ key ];        
        Object.assign( resolvedPromiseObject, { [ key ]: value } );
    }
    return resolvedPromiseObject;
}

Answer №1

To access the values of properties within a Promise, you can iterate over them and utilize the Awaited utility type.

type AwaitedProperties<T> = {
  [Key in keyof T]: Awaited<T[Key]>
}

Example:

interface IDataPromises {
  dataPromise1: Promise<number>;
  dataPromise2: Promise<string>;
}

type ResolvedDataPromises<T> = {
  [K in keyof T]: Awaited<T[K]>
}

type IResolvedDataPromises = ResolvedDataPromises<IDataPromises>
// type IResolvedDataPromises = {
//    dataPromise1: number;
//    dataPromise2: string;
// }

Playground

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

User-initiated closure of popup triggers error during Google sign in

After successfully implementing Google signin locally, I encountered an issue when attempting to login on a server. The error message displayed was: 'Uncaught: popup closed by user' Despite disabling adblockers and other potential interference, ...

Guide to implementing optional localization strings in React-Router paths

Incorporating react-router, I aim to implement internationalization for links following this format: domain.com/langISO/countryISO2/page Here are some examples of valid routes: domain.com/ -> Home Page domain.com/en/us -> Home Page domain.com/fr/f ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

Turn off the header display for the login page

I have an angular js app with an index.html page that loads all the scripts and a default header present in all the views. Here is my index.html: <!doctype html> <html class="no-js"> <head> <meta charset="utf-8"> <title ...

Guidelines for transferring JavaScript array data to a csv file on the client side

Despite the abundance of similar questions, I am determined to tackle this using JavaScript. Currently, I am utilizing Dojo 1.8 and have all attribute information stored in an array structured like this: [["name1", "city_name1", ...]["name2", "city_name2" ...

What could be hindering my jQuery function from running the Ajax script?

My jQuery function is supposed to retrieve two values, one for school/college and one for state, and send it to the controller class under the URL "Type&State". However, for some reason, the data is not being passed and nothing is shown in the console ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: https://i.sstatic.net/GL3Fd.png The challenge I am facing involves updating the language of the chips based on the sele ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

Utilizing html5 mode in AngularJS alongside an external NodeJS server

Despite reading numerous SO answers and questions on this topic, I still find myself with lingering uncertainties. To outline the issue: I am utilizing an AngularJS app with html5 enabled to eliminate the '#' sign. $locationProvider.html5Mode( ...

Can undefined be forcibly assigned with strict null checks enabled?

Considering enabling the strictNullChecks flag for a TypeScript project I've been developing leads to numerous compiler errors. While some of these errors are relevant edge cases, many follow a specific pattern. type BusinessObject = { id: string; ...

Resolving the problem of <Link> error in React with Typescript using react-router-dom

Currently, I am facing an issue with the 'react-router-dom' library. This is my first experience using React with Typescript; Everything was functioning properly until I introduced the from 'react-router-dom', which caused the entire ...

Checking the service callback function in an AngularJS controller test

I have a Controller that utilizes a service with a callback function upon success. Controller Function itemCtrl.save = function () { ItemService.save({ username: SessionService.getUsername() }, itemCtrl.item, function (res) { $scope.$emit(&ap ...

Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple. public showDialog(theNickname: string): string { var req = { method: 'POST', url: '/Q/GetUserDetails', data: { nickname ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

`Where can I find resources on connecting components in Angular 2?`

Exploring ways to enhance my website, I am considering allowing users to customize the theme according to their preferences. To start off, I decided to introduce a 'Dark theme' option. In order to implement this feature effectively, I am working ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

You have encountered an issue with the runtime-only build of Vue, which does not include the template compiler

Lately, I have been utilizing Vue in a project and encountered an issue where upon compiling, my browser page displays as white with an error message stating "You are using the runtime-only build of Vue where the template compiler is not available. Either ...

Having trouble dynamically displaying the '<' symbol using JavaScript?

Whenever I attempt to show a string with the character '<' in it, the part of the string that comes after the symbol is not displayed. Strangely enough, when I output it to the console, it appears correctly. Take a look at this excerpt showcas ...

Utilizing C in WebAssembly to return string values

Is it possible to retrieve a JavaScript string from a WebAssembly function? https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional C #include <stdio.h> #include <string.h> void jsPrintString(const ch ...