Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an array type in TypeScript

Tags:

typescript

I'm using TypeScript for a project and there's a case where I need to use Promise.all(...), which is returning an array of many items:

Promise.all(
  firstRequest,
  secondRequest,
  ...,
  nthRequest
)
.then((array : [FirstType, SecondType, ..., NthType]) => {
  // do things with response
});

Now, since the type [FirstType, SecondType, ..., NthType] is too long to be defined there, I wanted to define it elsewhere and use it in that point.

So I tried:

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

And:

.then((array : ResponseParams) => {
  // do things with response
});

But I receive this error:

Type 'ResponseParams' is not an array type.

How can I externalise the type and make my code cleaner?

Thank you

like image 342
Cristian Traìna Avatar asked Dec 21 '25 00:12

Cristian Traìna


1 Answers

You can define such a type using a type alias:

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

But I would point out that the type of array will be inferred without explicit type annotation (at least 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 of type [{a: number;}, {b: number;}, {c: number;}]      
// do things with response
});
like image 114
Titian Cernicova-Dragomir Avatar answered Dec 24 '25 11:12

Titian Cernicova-Dragomir