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
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With