Issue with asynchronous function: "Cannot assign type 'Promise<MyType[]>[]' to type 'MyType[]'"

After converting this function to async, I've been encountering issues with type annotations being out of sync:

export default async function formatCallRecordsForPGPromise(
  rawCalldata: CallRecord[],
): Promise<SaveableCallRecord[]> {
  const dataSortedbyPhoneNumber: PhoneNumberKeyedCallData = lodash.groupBy(rawCalldata,
    (record: CallRecord) => record.destination);

  const phoneNumberAndGroupedData: [string, CallRecord[]][] = Object
    .entries(dataSortedbyPhoneNumber);

  const allData: Promise<SaveableCallRecord[]>[] = phoneNumberAndGroupedData
    .map(async (numberAndCallData: [string, CallRecord[]]) => {
      const phoneNumber = numberAndCallData[0];

      const selectCampaignId = 'SELECT id FROM campaign WHERE phoneNumber = $1';

      let campaign_id: number;
      try {
        campaign_id = await pgp.configured.one(
          selectCampaignId, phoneNumber, (queryResult: { id: number }) => queryResult.id,
        );
      } catch (error) {
        throw new Error(error);
      }

      const formattedDataSet: SaveableCallRecord[] = numberAndCallData[1]
        .map((record: CallRecord) => {
          const {
            date, callerid, destination, description, account, disposition, seconds, uniqueid,
          } = record;

          const formattedData: SaveableCallRecord = {
            unique_id: uniqueid,
            caller_id: callerid,
            <more 
          };

          return formattedData;
        });

      return formattedDataSet;
    });

  const allDataFlattened = allData.flat();

  return allDataFlattened;
}

Error:

/*
const allDataFlattened: Promise<SaveableCallRecord[]>[]
Type 'Promise<SaveableCallRecord[]>[]' is not assignable to type 'SaveableCallRecord[]'.

Type 'Promise<SaveableCallRecord[]>' is missing the following properties from type 'SaveableCallRecord': unique_id, caller_id, date, description, and 4 more.ts(2322)
*/

I have tried several minor tweaks but can't get the annotations to pass without lint errors. The desired return type is an array of SaveableCallRecord. Can anyone see the issue?

Update

  const allDataFlattened = (await allData).flat();

I get this error:

/*
const allDataFlattened: Promise<SaveableCallRecord[]>[]
Type 'Promise<SaveableCallRecord[]>[]' is not assignable to type 'SaveableCallRecord[]'.
  Type 'Promise<SaveableCallRecord[]>' is missing the following properties from type 'SaveableCallRecord': unique_id, caller_id, date, description, and 4 more.ts(2322)
*/

Update 2

  await Promise.all(allData);

  const allDataFlattened = allData.flat();

  return allDataFlattened;

Error remains the same.

I am still unsure how to solve this, although I continue to try. Any help is appreciated.

Answer №1

My coworker recently mentioned to me that the TSC compiler is unable to automatically determine promise resolution for allData.

Prior Code

await Promise.all(allData);

const allDataFlattened = allData.flat();

return allDataFlattened;
// updated code:
return Promise.all(allData).then((data) => data.flat())

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

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

Discover every possible path combination

Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example: // Given input array with single elements or 1D arrays: let input = [1, 2, [3, 4], [5, 6]]; The unfolding process splits pa ...

Translating Python's slicing assignment syntax to JavaScript/TypeScript: A guide

Currently, I am in the process of converting a Python library into TypeScript. One specific challenge I am facing is translating this line of code from this particular repository: is_prime[start - segment_min::pk] = repeat(False, len(range(start - segment ...

In Angular 4, the Bootstrap modal now only opens after a double click instead of opening on the first click

Working on an eCommerce application, there is a cart icon that triggers a modal screen displaying user-selected product data when clicked. However, the issue I'm facing is that upon initial page load, the modal screen opens only after double-clicking; ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

Organizing string enum in Typescript and AngularJS - Tips and Tricks

In my Typescript file, I have defined an enum called PriorityLevel: enum PriorityLevel { High = <any>'High', Normal = <any>'Normal', Low = <any>'Low'} In the HTML section, I have the following code: <b ...

The "path" parameter must be a string data type in order to proceed. The value received is currently undefined

My current project is utilizing Angular 8 When I attempt to run 'ng build --prod', my project encounters errors. ERROR in The "path" argument must be of type string. Received type undefined The issue arose after adding "enableIvy": true to the ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Angular version 12 (node:3224) UnhandledPromiseRejectionWarning: Issue encountered with mapping:

Trying to generate the translation file in my Angular project using the command ng extract-i18n --output-path src/translate, I encountered this error message: \ Generating browser application bundles (phase: building)...(node:3224) UnhandledPromiseRej ...

How to calculate the sum of all values in a FormArray in Angular

I am trying to retrieve the input values from each row and then calculate the sum of these rows. Here is my HTML code: <ng-container formArrayName="cap_values"> <tbody *ngFor="let item of capValues.controls; let i=index" [formGroupName]="i"& ...

Searching for a way to access the HTTP request header using ReactJS?

Can anyone assist me in retrieving the request header's cookie? I have searched extensively but haven't found a satisfactory document. Please share with me a reliable solution. ...

Using Selenium WebDriver with JavaScript: Handling Mouse Events (mouseover, click, keyup) in Selenium WebDriver

I am currently working on integrating Selenium testing for mouse events with dynamically generated elements. Specifically, I am attempting to trigger a "mouseover" event on an element and then interact with some icons within it. However, I have encountere ...

Potential absence of value in this Vue 3 component's 'this' placement

I've been encountering an issue with using this.$refs within my Vue component. No matter where I place it - whether in methods, lambdas, or lifecycle hooks - I consistently receive errors indicating that 'this' may be undefined. As a newcome ...

Can TypeScript interfaces be used to achieve the same functionality as an abstract class?

I am currently working on developing a function that will return an array type with custom methods, allowing me to utilize it across various sections of the application. Typically, this is achieved using Abstract Classes where abstract methods are defined ...

Angular removing every query string parameters

Linked to but distinct from: How to maintain query string parameters in URL when accessing a route of an Angular 2 app? I am facing an issue with my basic Angular application where adding a query parameter results in its removal, both from the browser&apo ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Creating a specialized TypeScript interface by extending a generic one

Create a customized interface using TypeScript that inherits from a generic interface by excluding the first parameter from all functions. Starting with the following generic interface: interface GenericRepository { insertOne<E>(entity: Type<E& ...

Property does not exist when dispatching in React Redux within componentDidMount

Currently, I am navigating my way through my initial project using React + Redux and have hit a few roadblocks while attempting to dispatch a function in the componentDidMount section. I tried to emulate the Reddit API example project from the Redux docume ...

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...