Using TypeScript and encountering Error TS2345 when trying to utilize Promise.all() in a dialog component

I have a TypeScript function that I need help with:

    private async deleteSelectedLuminaires (): Promise<any[]> {
    return this.dialogService.open({ viewModel: DeleteLuminaire, model: 'Cancel or Ok', lock: false })
    .whenClosed((response) => {
      if (!response.wasCancelled) {
        const requests = this.selectedSerials
          .map(async (serial) => this.luminaireApi.removeLuminaire({ serial }))

        return Promise.all(requests)
      }
    })
  }

The function this.luminaireApi.removeLuminaire returns Promise< void >. I am encountering an error when using the Dialog service to ask a question in this function. After deleting the dialog, I receive the following error message:

error TS2345: Argument of type '(response: DialogCloseResult) => Promise | undefined' is not assignable to parameter of type '(value: DialogCloseResult) => any[] | PromiseLike'. Type 'Promise | undefined' is not assignable to type 'any[] | PromiseLike'. Type 'undefined' is not assignable to type 'any[] | PromiseLike'.

I believe the issue lies in combining dialog and Promise.all, but I am unsure of the exact reason. Could someone please assist me in resolving this problem?

Answer №1

It appears that there is a function in your codebase that could potentially return either a Promise or undefined, implying that there might be a missing return statement in one of the code branches.

This scenario is represented by

(response: DialogCloseResult) => Promise | undefined
.

To resolve this issue, you should ensure that the method responsible for handling a DialogCloseResult consistently returns a Promise and not undefined. If you cannot modify the signature of this method, consider using a type guard or type assertion to handle the return value appropriately.

Type Guard

if (typeof returnValue !== 'undefined') {
    // This block handles when the return value is a Promise
}

Type Assertion

promiseValue = <Promise>returnValue;

Answer №2

Below is my solution to the problem:

async function deleteSelectedItems(): Promise<any> {
    let promises: Promise<any>

    return this.confirmationDialog.open({ viewModel: ConfirmDelete, model: 'Cancel or Confirm', lock: false })
        .whenClosed(async (response) => {
            if (!response.wasCancelled) {
                promises = Promise.all(this.selectedItems
                    .map(async (item) => this.api.removeItem({ id: item.id })))
            }

            return promises
        })
}

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

What is the best way to pass the modal dialog parameter sent from HTML to the TypeScript page?

I have implemented a dialog window using Angular where it opens by passing a parameter in the HTML side along with a transaction. To further enhance the functionality of my page, I want to incorporate the fab button. However, I am facing a challenge in sen ...

To properly display a URL on a webpage using Angular, it is necessary to decode

After my console.log in Angular 5 service call to the component, I can see the correct data URL being displayed http://localhost:4200/inquiry?UserID=645 However, when it is inside an Angular for loop in the HTML template, it displays http://localhost:42 ...

Updating data through SessionStorage.set() method isn't reflecting changes

I am facing an issue with the code below, as the sessionstate does not seem to update properly. The initial result shows 3 social security numbers, but after attempting to update it with 100 new numbers, the count remains the same. Any insights on why th ...

PIXI.js fails to optimize image loading and loads the same image multiple times when a base URL is used

I'm in the process of developing a game using PIXI.js that will be accessed through URL X but loaded on another website at URL Y. To make this possible, I've implemented an environment variable called BASE_URL. This variable is set to '&apo ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

What is the process for integrating a third party API certificate into my Heroku application?

When my backend service calls a third-party API (Kamer van koophandel) to retrieve data, it requires a certificate to be set. It functions correctly locally, but upon pushing to Heroku, the following error occurs: Warning: Ignoring extra certs from `Privat ...

Validating Forms in TypeScript

Currently in the process of learning Angular 10, but encountering a challenge I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button c ...

Best practices for safely handling dynamic keys in Typescript

I am searching for a secure method to create keyed objects in this manner: interface Types { RED: 'RED'; BLUE: 'BLUE'; GREEN: 'GREEN'; } type TypeKeys = keyof Types; const COLORS: Types = { RED: 'RED', B ...

Selected structures in rust

Can a struct be selected in a way that the type checker can handle without any issues? Coming from TypeScript: // Assuming a main object type with all fields: interface User { id: number; name: string; password: string; }; // Using a picked t ...

No pipe named '' was discovered

I have created a custom pipe in Angular, but when I try to use it, I keep receiving the error message: "No pipe found with name 'RefPipe'". I have searched for solutions online and they all suggest importing the pipe. However, I have tried import ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...

Select characteristics with designated attribute types

Is there a way to create a type that selects only properties from an object whose values match a specific type? For example: type PickOfValue<T, V extends T[keyof T]> = { [P in keyof (key-picking magic?)]: T[P]; }; I am looking for a solution w ...

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

When using my recursive type on Window or Element, I encounter a type instantiation error stating "Type instantiation is excessively deep and possibly infinite.ts"

Recently, I have been using a type to automatically mock interface types in Jest tests. However, upon updating TypeScript and Jest to the latest versions, I encountered an error message stating Type instantiation is excessively deep and possibly infinite.t ...

Using TypeScript to pass an object's method as an argument in a function call

Recently, I delved into game development using cocos creator with TypeScript/JavaScript, languages that are still new to me. My current challenge involves creating a complex callback method that will trigger methods attached to an array of objects. Here&a ...

The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user t ...

One-of-a-kind npm module for typescript

As part of my project, I am enhancing an existing library to make it compatible with TypeScript. To showcase this modification, I have condensed it into a succinct Minimal working example The specified requirements To ensure backward compatibility, the li ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

Identifying the absence of a character at the end of the last line in Node.js to detect

Currently, I am processing data line by line from a buffer. Within the buffer, the data is structured as follows: name,email,phn test1,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332234337607223f262a372b226924282a">[em ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...