Incorporate generic types into Promise.props(...) using Typescript

I am currently working on developing a custom typed Promise.props(...) utility function that dynamically assigns correct types based on the input object.

static async props<T extends {[key: string]: Promise<S>|S}, S, U extends { [key in keyof T]: S}>(obj: T): Promise<U> {
    const promises = [];
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        promises.push(obj[key]);
    }
    const results = await Promise.all(promises);

    return results.reduce((map, current, index) => {
        map[keys[index]] = current;
        return map;
    }, {});
}

At this point, I have defined the type T as the input parameter and also specified U, which has identical keys but different value types.

I am wondering if it is possible to determine the result type from a Promise in the same way that I can extract the keys of an input parameter.

When using this function, the process should resemble the following example:

const result = await this.props({
    val1: Promise.resolve('test'),
    val2: Promise.resolve(123),
    val3: ['a', 'b', 'c']
});

As a result, the IDE should be able to infer that:

result.val1 is a string
result.val2 is a number
result.val3 is an array

Answer №1

Here is a possible solution:

async function fetchProps<T>(data: {[Key in keyof T]: Promise<T[Key]> | T[Key]}): Promise<T> {
  // (I haven't examined the actual code)
}

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

Does Apollo Federation provide support for a code-first development approach?

I have declarations using 'code-first' approach in my project, but now I want to utilize them as microservices. How can I separate my 'typeDefs' and 'resolvers' following Apollo's 'schema-first' methodology? Is ...

Updating an element within a for loop using Angular TypeScript

I'm trying to figure out how to update the value of an HTML DOM element that is bound from a TypeScript file in each iteration of a for loop, rather than at the end of the loop. I want to see all values as the loop is running. For example, imagine I ...

Modify the value of the <select> tag based on whether it is required or not

When utilizing a my-select.component within a form component, the following code snippet is used: <div *ngIf="items?.length"> <select [ngModel]="selectedItem" (ngModelChange)="valueChanged($event)"> <optio ...

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

Implementing Dynamic Updates to a Google Sheets Custom Menu using Typescript

How to Automatically Update a Custom Menu in Google Sheets using Typescript I have successfully set up the following: Dynamically Updating Custom Menu of Google Spreadsheet using Google Apps Script, a demonstration script for dynamically updating the cust ...

Avoid using React refs for managing Popups

Recently, I've been using a pattern based on refs that seems to go against the advice given in the React documentation. This is how the pattern works: type Callback = () => void; type CallbackWrapper = {callback : Callback} interface IWarningPop ...

Can a Typescript type alias be altered in real time?

Currently, I am developing an Angular library that will function as an API client. The challenge I am facing is that some of the applications utilizing this library are configured with an HttpInterceptor to automatically transform date strings into JavaScr ...

Extract a string value from a TypeScript enum

Here is a basic enum definition: export enum Type { TEST_ONE = "testing.one", TEST_TWO = "testing.two", BETA = "beta.one" } I am looking to run a function for each string value in the enum. For example: executeType(type: string) { console.lo ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

Tips on customizing a row in a table

Having a small issue styling a row in my table. Essentially, the table consists of 4 rows. a) If the data under column Title 5 is below 0, then the entire row should display in red color. b) If the data under column Title 5 is equal to 17, then the compl ...

Firefox unable to detect click events

I am facing an issue with my Angular 2 website where it is not functioning correctly in Firefox. The main problem lies in the fact that Firefox does not recognize the event being passed into my TypeScript function. This event specifically pertains to a mou ...

Utilizing Object.fromEntries in Typescript

I am attempting to define a type called ObjectFromEntries that functions similarly to the return type of the Object.fromEntries function. Here is what I have so far: type ObjectFromEntries<Entries extends [keyof any, any][]> = { [key in Entries[numb ...

Is there any object serialization library in Delphi that includes support for Generics?

From my knowledge, none of the open source object serialization libraries I am familiar with (such as JvAppStorage, NativeXml, OmniXML, SuperObject, lkJSON) currently support Generics properties. (Please inform me if this information is incorrect). Are yo ...

What is the reason for the inability to import a router for express in TypeScript?

I have been working on setting up a basic Hello World REST service using NodeJS and Typescript. I attempted to organize the routers into separate files, but encountered some issues along the way. Specifically, when making a GET call to http://localhost:30 ...

Troubleshooting the TS2559 error when using radium in React typescript: CSSProperties type mismatch

Looking to integrate Typescript into React and incorporate some styling using Radium. I understand that JSX style does not support media queries, but I'm unsure how to resolve this issue. Can anyone provide guidance? Thank you! Encountering errors w ...

Issue with PrimeReact dropdown component not recognizing an array in TypeScript

Trying to incorporate the PrimeReact Dropdown component in a NextJs app with TypeScript. Encountering an error when attempting to select options from the dropdown list: "Objects are not valid as a React child (found: object with keys {name, code})" The b ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

Uncover the contents of a JSON array by employing generics and leveraging the power of

I'm currently working on an app to gain a better understanding of using generics in Swift. To achieve this, I decided to utilize Studio Ghibli's API Here's my approach: Send a request to the API Receive the response Parse the JSON data T ...

The 'undefined' type cannot be assigned to the 'never' type

interface A { name?: string age: number } var a: A = { name: '', age: 23 } var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => { if (a[key] || a[key] === 0) { prev[key] = a[key] // an error was reporte ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...