Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10464

Define an array type in 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

Upvotes: 3

Views: 169

Answers (2)

k0pernikus
k0pernikus

Reputation: 66748

Promise.all accepts a generic T, which gives you full control over the return type. You can thereby define the tuple for each promise that you expect back while still maintaining the types.

I would do it this way 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);

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250216

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
});

Upvotes: 2

Related Questions