What type will the click handler return be determined by TypeScript?

I am working on a custom button control that has a click handler which can either return a promise or void. Here is an example of the button options interface and the click handler:

// --- Options for button control
export interface buttonOptions {
   aProperty: string
   anotherProperty: number
   onClick: Promise<IButtonClickResult> | void
}

// --- Click handler added for click event inside control class
protected clickHandler(): Promise<IButtonClickResult> | void {
   if(returnsPromise) displaySpinner()

   various operations

   this.options.onClick(this)
}

To create the control using the builder pattern, you would do the following:

buttonClass.build()
  .options({
      aProperty: 'Hope this works',
      anotherProperty: 1,
      onClick: () => {
          return new Promise<IButtonClickResult>((resolve, reject) => {         

            // --- I suppose I could pass reference to resolve or reject to async function and allow that function to resolve or reject the promise
            asyncOperation(resolve, reject)                         
          }).then((result) => button.onClickSuccess(result)).catch((error) => button.onclickError(error))

You can also assign a function to onClick that returns void:

console.log('I was clicked')

If the click handler returns a promise, I want to show a spinner on the button until the promise is resolved or rejected. My question is how can I determine if a promise will be returned so I know when to display the spinner. Any guidance on this issue would be greatly appreciated. I have tried using typeof and instanceof, but I have not been successful so far. I might not be using them correctly as I am still new to TypeScript and NodeJS.

Answer №1

To handle a union type, you can use conditional testing to navigate through the `void` branch (assuming `strictNullChecks` is enabled):

const result: Promise<IButtonClickResult> | void = this.onClick(...args);
if (result === undefined) {
  // No return value, skip async operation
} else {
  // Since result is now a Promise, you can use methods like .then in TypeScript
}

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

You cannot assign type void to type any

I'm currently working on a component that involves some code: export class AddNewCardComponent { public concept = []; constructor( private _router: Router, private _empDiscService: empDiscService) { } ngOnIni ...

Updating button color dynamically using Angular 2

I am working on a project using angular 2 and typescript. I am looking to customize the background color of my buttons based on a variable. <div> <button md-button>1. Choose travel</button> <button md-button>2. Choose seats< ...

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

Creating custom components that encapsulate the functionality of Angular Material tabs component

I am aiming to incorporate the Angular Material tabs component within my shared components. Here is the component I'm attempting to wrap: Note: Each tab can display a component: <mat-tab-group> <mat-tab label="First"> Content ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

issue with Angular: Unable to set both minimum and maximum values in the same input field for date type

I have been attempting to apply minimum and maximum values to an Angular code snippet, here is what I have: <input type="date" class="form-control" style="width: 30%" [disabled]="!dateSent" min="{{dateSent|date:&apo ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

What could be the reason for my function throwing a TypeError with the message "<function> is not a function"?

Every time I try to call a function that clearly appears to be defined as a function, I continuously receive the error message: TypeError: [function name] is not a function. To demonstrate the issue, here is a simple example: main.ts import someFunction ...

Prevent modal from closing when clicking outside in React

I am currently working with a modal component in react-bootstrap. Below is the code I used for importing the necessary modules. import React from "react"; import Modal from "react-bootstrap/Modal"; import ModalBody from "react-bootstrap/ModalBody"; impor ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Swap out each addition symbol with a blank space within a given text

I'm currently working on a Typescript project where I need to convert URL parameters into a JSON object. The issue I'm facing is that some values are concatenated with a '+'. How can I replace this symbol with a space? Here's the ...

Encasing distinct HTML text with a custom color palette

How can I create a specific color scheme for my HTML table's Status parameter, where the values can be SUCCESS, FAILURE, or IN PROGRESS? I'm utilizing Angular 4 (HTML and TypeScript) for this task. Any tips on how to achieve this? ...

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...

Where should the defer.resolve be placed when executing a function asynchronously in a loop using JavaScript?

As someone coming from a java/python background, I am venturing into the world of JavaScript. My current task involves creating a product list with detailed descriptions of its children included in a JSON array. Here is an example of what I want to achiev ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

The issue with error handling in Angular's $http component

My Angular application is failing to properly handle errors in $http requests. I've set up a $httpProvider where I use $q.reject(response) in the error response as instructed by the documentation. However, when an error occurs, all I see in the conso ...

Error with Background component in Next.js-TypeScript when trying to change color on mouseover because Window is not defined

Within my Background component, there is a function that includes an SVG which changes color upon mouseover. While this functionality works fine, I encountered an error when hosting the project using Vercel - "ReferenceError: window is not defined." This i ...