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

Can we create a class to represent a JSON object?

Can a JSON be modeled with a class in TypeScript (or Angular)? For example, I am using Firebase and have a node called /books structured like this: books -- 157sq561sqs1 -- author: 'Foo' -- title: 'Hello world' (Where 1 ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...

The issue with Angular2 Material select dropdown is that it remains open even after being toggled

Exploring the world of Node.js, I am delving into utilizing the dropdown feature from Angular Material. However, an issue arises once the dropdown is opened - it cannot be closed by simply clicking another region of the page. Additionally, the dropdown lis ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

Can you explain the distinction between an optional field and a union?

Is there a significant distinction between the following structures: { ok: boolean; } | { ok: boolean; error: any; } and: { ok: boolean; error?: any; } I have observed variance in the inferred types of frontend methods' return ou ...

Error: WebStorm's Language Service has timed out while executing TSLint operations

While working on my Mac running MacOS Sierra with WebStorm (version 2017.2.4), I encounter a pop-up notification sporadically, as shown in the following image: My coworkers and I all have the same TSLint configuration and code style set up in WebStorm. Ho ...

Issues with showing data in Angular Material tables

I recently deployed my Angular Application on a server and encountered an issue with the Angular Material table. Despite data being present in the logs, it does not display on the table. This problem only occurs in production, as everything works perfectl ...

Verify if an item is present within a separate array

To determine if an object in one array exists in another array, we can use the combination.some() method with a condition that checks for a match based on specific criteria. In the example below, the event array returns true while the event1 array return ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

Forwarding refs in React FC allows you to easily pass down

I have encountered an issue with references - I am trying to reference a function component and pass props to it. Currently, I have my Parent component and Child Component set up. In the parent component, I need to use a ref to access my child component. S ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

The process of sorting through an array of objects based on their specific types in TypeScript

I am working on a function that filters an array of objects based on their type property: export const retrieveLayoutChangeActions = (data: GetOperations['included']) => data.filter(d => d.type === 'layoutChangeAction') as Layou ...

What factors contribute to the variations in results reported by Eslint on different machines?

We initially utilized tslint in our project but recently made the switch to eslint. When I execute the command "eslint \"packages/**/*.{ts,tsx}\"" on my personal Windows machine, it detects 1 error and 409 warnings. Surprising ...

What is the importance of adding the ".js" extension when importing a custom module in Typescript?

This is a basic test involving async/await, where I have created a module with a simple class to handle delays mymodule.ts: export class foo { public async delay(t: number) { console.log("returning promise"); ...