Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute:

function extendPromise(promise) {
    return promise.then(new Promise(() => {}));
}

However, when incorporating types into the mix, such as

function extendTypeScriptPromise(promise: Promise<void>) {
    return promise.then(new Promise<void>(() => {}));
}

the TypeScript compiler raises an objection:

error TS2345: Argument of type 'Promise<void>' is not assignable to parameter of type '((value: void) => void | PromiseLike<void>) | null | undefined'.
  Type 'Promise<void>' is not assignable to type '(value: void) => void | PromiseLike<void>'.
    Type 'Promise<void>' provides no match for the signature '(value: void): void | PromiseLike<void>'.

Why isn't a Promise<void> accepted as PromiseLike?

Answer №1

Your JavaScript code needs some adjustments to be correct. The argument of Promise.then() should be a function, not another Promise.

This function can return a new Promise, void, or a non-promise value that resolves the Promise being used with .then(). In your case, it should return a new Promise.

The accurate JavaScript code is:

function extendPromise(promise) {
    return promise.then(() => new Promise(() => {}));
}

and the corresponding TypeScript code would be:

function extendTypeScriptPromise(promise: Promise<void>) {
    return promise.then(() => new Promise<void>(() => {}));
}

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

How can I utilize generic types in Typescript/React when crafting a component with prop types?

I am facing an issue with a component that has a generic definition as shown below: export type CheckboxItem = { label: string, code: string, }; export type CheckboxesProps = { items: CheckboxItem[], handleStateChange: (selected: (CheckboxItem[&ap ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Issue with Angular2 discount calculation formula malfunctioning

I'm encountering a rather perplexing issue with Angular2/Typescript. My goal is to compute the final price based on a specified discount value. Here's the formula I am using: row.priceList = row.pricePurchase + (row.pricePurchase * row.markUp / ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...

Can we verify the availability of an Angular library during runtime?

I am in the process of creating a custom Angular library, let's name it libA, which has the capability to utilize another Angular library, named libB, for an optional feature. Essentially, if the Angular application does not include libB, then the fea ...

Angular 2: Obtaining the caret position in a contenteditable 'div'

Take a look at this code snippet: <div #test (click)="onClick(test)" contenteditable="true"> This text can be edited by the user. </div> @ViewChild('test') el:ElementRef; constructor(private elementRef: ElementRef) {} ...

Angular reactive forms are experiencing a setback where the value of '[value]' is not being properly set for controls

My scenario is as follows: <input #physicalAddress1 type="text" formControlName="PhysicalAddressLine1" /> <tfg-toggle #physicalAsPostal formControlName="PhysicalAsPostal" [onText]="'Yes'" [offText ...

Error encountered: "Injection error: Angular2 + typescript + jspm : No provider found for Http ( App -> Provider -> Http )"

I am in the process of transitioning from Webpack to JSPM with system.js. Our application has a simple App component. I have been following the steps outlined in this article Angular 2 Starter Setup with JSPM, SystemJS and Typescript in atom (Part 1) impo ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...

What are the best practices for utilizing generics effectively?

A series of interfaces has been defined: export interface FormData<T extends ControlData = any> { [type: string]: T; } export type FormResult<T extends FormData> = { [type in keyof T]: T[type]; }; export interface ControlData<T = any& ...

When it comes to rendering components in React using multiple ternary `if-else` statements, the question arises: How can I properly "end" or "close" the ternary statement?

I have developed a straightforward component that displays a colored tag on my HTML: import React, {Component} from 'react'; import "./styles.scss"; interface ColorTagProps { tagType?: string; tagText?: string; } /** * Rende ...

TSLint Alert: Excessive white space detected before 'from' keyword (import-spacing)

I'm currently using WebStorm and working to maintain a specific code style: However, I encounter an issue where TSLint highlights my spacing and provides the following hint: "Too many spaces before 'from' (import-spacing)". My main ques ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

What is the best way to check the API response status in NextJS13?

Currently, I am experimenting with different methods to handle API HTTP status in my NextJS-13 project but so far nothing has been successful. Note: TypeScript is being used in this project. Below is my code snippet with a static 200 API response and the ...

Unable to load custom package in Angular 2 testing environment

I've been following the official Angular 2 testing guide on an existing project. Everything runs smoothly when I use my custom library, downloadjs, in the application. However, I encounter an error in the console during test execution: "__zone_symbol ...

What is the best method for sharing templates and logic in VUE?

Two separate components with shared logic and template, making it appear as though one is extending the other. Think of Drop and Pick components in this manner: // pick.js import Vue from 'vue' import Component from 'vue-class-component& ...

TypeScript maintains the reference and preserves the equality of two objects

Retrieve the last element of an array, make changes to the object that received the value, but inadvertently modify the original last position as well, resulting in both objects being identical. const lunchVisit = plannedVisits[plannedVisits.length ...