Is there a syntax available for type annotation of arrays created from pre-declared variables?

According to my standards, all possible annotations are required in TypeScript. Therefore, TypeScript-ESLint is prompting me to annotate the `[ responseData, cognitoUser ]`. However, when I try to use the syntax `[ responseData1: ResponseData1, responseData2: ResponseData2]`, I receive an error message (`TS1005: ';' expected`). If this syntax doesn't work, it might be an issue with the TypeScript/ESLint repository.

let responseData1: ResponseData1;
let responseData2: ResponseData2;

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

Answer №1

In TypeScript 4, it's now possible to include labels for array types.

type DataResponse = [data1: DataResponse1, data2: DataResponse2];

This feature can be utilized when using Promise.all:

try {
  const [data1, data2]: DataResponse = await Promise.all([ /* ... */ ]);
} catch {
 // Handle error
}

Answer №2

When using destructuring with Promise.all, it is important to follow this overall pattern and handle errors:

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

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

async function combineResults(): Promise<{ fetched: number; retrieved: number }> {
  try {
    const [fetched, retrieved] = await Promise.all([fetchNumber(), retrieveNumber()]);
    return { fetched, retrieved };
  } catch (error) {
    throw new Error("An error occurred while combining results.");
  }
}

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

Is there a possibility that typescript decorators' features will be polyfilled in browsers lacking ES5 support?

According to the typescript documentation, a warning is issued: WARNING  If your script target is lower than ES5, the Property Descriptor will be undefined. If the method decorator returns a value, it will act as the Property Descriptor for the method. ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Using @Input to pass data from a parent component to a

Looking to modularize the form code into a separate component for reusability? Consider using @Input and referencing it in the HTML to pass values to the post method. Here's how you can achieve this: Previously, everything worked smoothly when all th ...

Need help resolving the issue of "Type Property '' does not exist on type 'IntrinsicAttributes & Function'? Let's find a solution together

Looking at my parent component below: import FilterComponent from 'filter/filterComponent' const handleReload = useCallback( (event: MouseEvent) => { event.preventDefault(); // implement logic here }, [Reload, Fetch ...

Here are some steps to turn off browser autocomplete for a p-inputMask field

I need help in disabling the browser autocomplete on a field that uses p-inputMask. I have tried using autocomplete="nope" on other fields and it works perfectly, but for this specific case, it doesn't seem to work. Can anyone point out what I might b ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

How can we ensure a generic async function with a return type that is also generic in Typescript?

I'm currently working on a function that retries an async function multiple times before rejecting. I want to make sure the typescript typings of the retry function are maintained and also ensure that the passed function is of type PromiseLike. Creat ...

Using the Angular Slice Pipe to Show Line Breaks or Any Custom Delimiter

Is there a way in Angular Slice Pipe to display a new line or any other delimited separator instead of commas when separating an array like 'Michelle', 'Joe', 'Alex'? Can you choose the separator such as NewLine, / , ; etc? ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...