Is some syntax exists for type annotation of decomposed to declared in advance variables array?

173 views Asked by At

In my standard, all types annotations where possible are required, so TypeScrit-ESLint tells me to annotate the [ responseData, cognitoUser ]. However, the syntax [ responseData1: ResponseData1, responseData2: ResponseData2] is invalid (TS1005: ';' expected). If there is no such syntax, it's the issue in TypeScript/ESLint repository.

let responseData1: ResponseData1;
let responseData2: ResponseData2;

try {
  [ responseData1, responseData2] = await Promise.all([ /* ... */ ])
} catch {
 // ...
}
2

There are 2 answers

1
Martin On

From TS 4 you can add labels for array types.

type ResponseData = [responseData1: ResponseData1, responseData2: ResponseData2];

And you can use it for your Promise.all:

try {
  const [responseData1, responseData2]: ResponseData = await Promise.all([ /* ... */ ])
} catch {
 // ...
}
6
Ali Habibzadeh On

Here is a overall pattern you need to follow for destructuring from Promise.all and catch the errors:

function getFoo(): Promise<number> {
  return Promise.resolve(2);
}

function getBar(): Promise<number> {
  return Promise.resolve(3);
}

async function getResults(): Promise<{ foo: number; bar: number }> {
  try {
    const [foo, bar] = await Promise.all([getFoo(), getBar()]);
    return { foo, bar };
  } catch (e) {
    throw new Error("something went wrong.");
  }
}