The type 'Promise<any[]>' cannot be assigned to the specified type

Here is my unique interface:

interface MeetingAttributeRecords {
  branches: Array<Promise<any>>;
  worshipStyles: Array<Promise<any>>;
  accessibilities: Array<Promise<any>>;
}

Below is a simplified version of my specific controller:

export const getAllMeetings = async (req, res) => {
  const meetings = await query(
    `SELECT * FROM meeting;`
  );

  const promises: MeetingAttributeRecords = getMeetingAttributeRecords(meetings);

  Promise.all([
    Promise.all(promises.worshipStyles),
    Promise.all(promises.branches),
    Promise.all(promises.accessibilities)
  ]).then(() => {
    res.json({ meetings: meetings.rows });
  });
};

Also, here is the utility function that conducts additional queries and returns promises:

export async function getMeetingAttributeRecords(meetings) {

  const branches = await meetings.rows.map(async (meeting) => {
    const branch = await query(
      // SQL CODE
    );
    return meeting.branch = branch.rows;
  });

  const worshipStyles = await meetings.rows.map(async (meeting) => {
    const ws = await query(
      // SQL CODE
    );
    return meeting.worship_style = ws.rows;
  });

  const accessibilities = await meetings.rows.map(async (meeting) => {
    const access = await query(
      // SQL CODE
    );
    return meeting.accessibility = access.rows;
  });

  return [branches, worshipStyles, accessibilities];
}

I am encountering the following Typescript errors:

[ts]
Type 'Promise<any[]>' is not assignable to type 'MeetingAttributeRecords'.
  Property 'branches' is missing in type 'Promise<any[]>'.

I have been researching extensively but haven't found a solution yet. Any insight would be greatly appreciated!

If you require any further details, please do let me know!

Answer №1

The function getMeetingAttributeRecords is currently returning an array instead of a format compatible with MeetingAttributeRecords.

To fix this issue, update the return statement to be like this:

return {branches, worshipStyles, accessibilities};
. This change should address the specific error mentioned.

Answer №2

Big thanks to everyone who shared their insights. As Frank Modica pointed out, I made the mistake of trying to return an array of promises as a single promise. The issue stemmed from how I was handling that singular promise in the route.

Instead of using Promise.all, I should have treated the single promise as a thenable object:

const promises = getMeetingAttributeRecords(meetings);

promises.then(() => {
    res.json({meetings: meetings.rows});
});

I had mistakenly assumed that I had multiple promises to resolve, when in fact there was only one!

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

ZOD distinguishes between unions based on two discriminator fields

I need to differentiate between two fields in a schema: enum Action = { CREATE: 'create' } enum ObjectType = { Potatoe: 'potatoe', Tomatoe: 'tomatoe' } export const TestSchema = z.object({ action: z.nativeEnum( ...

Extracting decimal number from a string using jq

I have a specific set of JSON data that includes floating values which I need to process conditionally across an array of JSON objects. Here is an example of one JSON instance: [ { "a": "0", "b": "66.67", "c": "0", "d": "0" } ...

Frequency of MySQL occurrences within a specified range of dates

I currently have a MySQL database structured like this: Date Customer_ID Is there a way to transform it into the following format? Customer_ID | Count_Visits_Past_Week | Count_Visits_Past_Month | Count_Visits_Past_90days | Count_Total Please note ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

Using a d.ts file is not possible for loading declaration merging

It functions perfectly well when everything is kept in the same file. declare module "express-session" { interface SessionData { userId: number; } } static async loginUser(req: Request, res: Response) { const { email, passwo ...

Implementing strict type enforcement for the `toString` method

Is there a way to prevent the compiler from overloading toString? I've tried using the never type, but it still allows implicit assignments and only raises an error when something is done with the variable. It's inconvenient to remember to explic ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

The efficiency of the Hive optimizer is lacking when it comes to handling joins with partitioned tables

I am currently utilizing Hive version 0.7.1-cdh3u2 In my database, I have two large tables known as A and B, both partitioned by day. I am executing the following query: select col1,col2 from A join B on (A.day=B.day and A.key=B.key) where A.day='20 ...

Even after rigorous type checking, TypeScript continues to throw the ts2571 error when handling an unidentified variable

Consider this scenario: the code snippet below will result in an Object is of type 'unknown'. error: let obj: {[key: string]: unknown} = {hello: ["world", "!"]}; // Could be anything with the same structure let key = "he ...

Efficient method of triggering an action on a subcomponent in React Redux without the need to pass props down the component tree

Currently in the process of learning how to utilize react, redux, and react-redux with a straightforward requirement. I aim to display something similar to the layout below... -------------------------------- | title 1 |----------| | | descriptio ...

What could be the reason for my inability to reach function attributes?

Struggling with accessing properties in a function that involves callback functions. const example = ( callback: (...args: unknown[]) => unknown ): void => ({ name: callback.name // <- errors // ... }) Encountering issues in typescript d ...

Is there a way to eliminate the " character from JSON within SQL or C# code?

I need to store JSON data in SQL Server and be able to read it as plain text without \r\n and \" Here is the code I am currently using to save the data to the database: JObject data=... objTableA.fieldA = data.ToString(Newtonsoft.Json.Form ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

The state array is rejecting the value from the other array, resulting in null data being returned

I am currently attempting to extract image URLs from an HTML file input in order to send them to the backend and upload them to Cloudinary. However, I am facing an issue where despite having the imagesArr populated with images, setting the images state is ...

Tips for categorizing the properties of an object based on their types

interface initialStateInterface { user: object; age: number; } const initialState = { user: { username: "", email: "" }, age: 0, }; In this code snippet, I have defined an interface type for the initial state containing a user ...

What is the best way to eliminate null values from my Java SQL results?

I'm having a hard time solving this problem and would appreciate any help you can offer. This method retrieves tags from my database by executing an SQL query, storing the results in an ArrayList, and then returning it. The database has 3 attributes ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

Discovering the initial appearance of a specific character sequence in T-SQL

Is there a straightforward method in T-SQL to identify the initial instance of either ',' or ';' within a string? I usually rely on regular expressions like [,;] in other database systems, but they are not supported in T-SQL. I've ...

Enhancing Angular 6 with Constructor Overloading

I'm a newcomer to TypeScript/Angular and I have a constructor set up to fetch JsonP. Now, I want to add a new constructor for HttpClientModule. Here's my current code: export class DataService { constructor(private _jsonp: Jsonp) { t ...