Create a new data structure in TypeScript that stores multiple values in a

For my TypeScript project, I came across a situation where I needed to utilize Promise.all(...) to handle an array of multiple items:

Promise.all(
  firstRequest,
  secondRequest,
  ...,
  nthRequest
)
.then((array : [FirstType, SecondType, ..., NthType]) => {
  // process the responses here
});

The type definition

[FirstType, SecondType, ..., NthType]
was too long to include in the same block, so I attempted to define it separately and refer to it at that point.

I tried the following approach:

export interface ResponseParams {
  [0]: FirstType;
  [1]: SecondType;
  ...
  [n]: NthType;
}

And then used it like this:

.then((array : ResponseParams) => {
  // process the responses here
});

However, I encountered the error message:

Type 'ResponseParams' is not an array type.

Is there a way to externalize the type declaration to improve the cleanliness of my code?

Appreciate any insights. Thank you!

Answer №1

To create a specific type, you can utilize a type alias:

type CustomType = [FirstType, SecondType, ..., NthType]

Keep in mind that the type of array can be automatically inferred without explicit annotation (for up to 10 promises):

declare let firstRequest: Promise<{a: number}>
declare let secondRequest: Promise<{b: number}>
declare let nthRequest: Promise<{c: number}>
Promise.all([
    firstRequest,
    secondRequest,
    nthRequest
])
.then((array) => { // array is determined as [{a: number;}, {b: number;}, {c: number;}]      
// perform actions with response
});

Answer №2

When using Promise.all, you have the ability to define a generic T, allowing for precise control over the return type. This enables you to specify the expected tuple for each promise while still preserving type integrity.

If I were to implement this using async / await syntax:

interface Foo {
    gnarf: string;
}

interface Bar {
    poit: string;
}

const createFoo = async (): Promise<Foo> => {
    return {
        gnarf: "random",
    };
};

const createBar = async (): Promise<Bar> => {
    return {
        poit: "hurz",
    };
};

const doStuff = async () => {
    const [foo, bar] = await Promise.all<Foo, Bar>([createFoo(), createBar()]);

    return `${foo.gnarf} and ${bar.poit}`;
};

doStuff().then(console.log).catch(console.error);

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

Dealing with a missing item in local storage in an Angular application

When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it ...

Obtaining the host name in server-side rendering (

In the process of developing an app that consists of a client and an API hosted on different domains, the setup resembles the following: [Local] localhost:5000 (client) localhost:5001 (API) [Web] app.domain.com (client) api.domain.com (API) When mak ...

Exploring the capabilities of Vue combined with Typescript and Audio Worklets

I've encountered a challenge with configuring Vue to compile audio worklets. Specifically, I am facing a similar issue to this problem that has already been resolved, but using Typescript instead of JavaScript. My approach was to include the ts-loader ...

Angular 14 Observables are not triggering resize events

There seems to be an issue here, as the code is not being triggered at all. The console log is not printing and this.width is not changing. constructor(private host: ElementRef, private zone: NgZone) {} public ngOnInit(): void { this.observer = new Re ...

A critical error has occurred: RangeError - The maximum call stack size has been exceeded while trying to

After attempting to filter a list of titles using Ng2SearchPipeModule, I imported the module in app.module.ts and created a new searchbar component. searchbar.component.ts import { FirebaseService } from './../../firebase.service'; import { Ang ...

"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality. dataSource: MatTableDataSource<MemberList>; @Output() walkthroughData: EventEmitter<number> = new EventEmitter(); @ViewChild(MatSort, { static: true }) sort ...

The TypeScript import statement is causing a conflict with the local declaration of 'Snackbar'

I'm having trouble using the Snackbar component from Material UI in my React app that is written in TypeScript. Whenever I try to import the component, I encounter an error message saying: Import declaration conflicts with local declaration of &apos ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

Why doesn't package.json typically utilize the preset values stored in the .npmrc file?

Windows 10 x64 Based on the information found here, I created a file called C:\Users\bushm\.npmrc with the following content: author = "Andrey Bushman" However, when I run the command npm init -y in a new directory, I noticed that the pac ...

Send properties to the component container

I am currently working on a higher order component that toggles between two children - a component that renders data and a loading component. The challenge I am facing is how to pass the loading state from the data component to the HOC for conditional rend ...

The search is on for the elusive object that Angular 2/4

Why am I encountering the error message saying "Cannot find name 'object'"? The error message is: Error: core.service.ts (19,23): Cannot find name 'object'. This error occurs in the following line of code: userChange: Subject<ob ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed: FormGroup { controls { products (FormArray) { 0 : {summary.value: 5}... 1 : {summary.value: 8}.. there can be N of these co ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

Enhancing Selectpicker options in Angular using data fetched from a web service

Having trouble with updating a selectpicker element within a subscribe method. I've included the code snippets below: Here is my HTML code: <div class="form-group col-md-2 pull-right"> <label for="city">City</label> <select ...

Ways to retrieve the document ID or address in TypeScript when using Firestore

I am currently developing a function that will send notifications to all devices where a user is logged in whenever a new order document is added to their account. Below is the code I have written to execute this function. My main query revolves around ac ...

How can you utilize an injected service from inside a Class decorator in Typescript/NestJS?

Can an injected service be accessed from within a Class decorator? I aim to retrieve the service in the personalized constructor: function CustDec(constructor: Function) { var original = constructor; var f: any = function (...args) { // How can I ...