TypeScript type declaration for promise.prototype.finally signature

I recently came across a ES6 Promise compatible finally implementation called promise.prototype.finally that I was using in a Node application. Now, I want to convert this application to TypeScript but unfortunately, I couldn't find any typings available for this package on DefinitelyTyped. In situations like these, I have created my own impromptu type definitions for the functionality that I require. However, given that this library modifies the prototype of the Promise object, I am unsure about how to represent it conventionally in TypeScript. Any suggestions or ideas?

Possibly related:

Answer №1

Slava's response is accurate, but it only addresses typing the finally block. To effectively integrate the shim into your code so that you can utilize p.finally(() => { ... }), you must execute the shim.

Regrettably, the typings on DefinitelyTyped currently do not support the shim function. Therefore, until this is rectified, it is recommended to manually incorporate the typings.

declare interface Promise<T> {
  finally<U>(onFinally?: () => U | Promise<U>): Promise<U>;
}

declare module 'promise.prototype.finally' {
  export function shim(): void;
}

The typings are now accessible. To install, use

npm install --save-dev @types/promise.prototype.finally

Within your TypeScript code, when initializing the application, call

import { shim } from 'promise.prototype.finally';
shim();

This action will implement the finally block in the Promise prototype, allowing usage of the finally feature as needed.

Answer №2

If you're looking to implement this without any shims, it's now possible with TypeScript 2.7. Keep in mind that as of February 26th, 2018, TS 2.7 is not fully ES2018 compatible yet. Although there are some things still missing, like Promise.finally which was added in the 2.7 release. While tsconfig-schema accepts ES2018 as a target, TS 2.7 doesn't have complete knowledge of ES2018. To access new features like Promise.finally in TypeScript 2.7, make sure to set your "target": "ESNEXT" in your tsconfig.json.

With this setup, you can write code similar to the following:

myAsyncFunction().then
(
  (var) => console.log("executing then. " + var)
)
.catch
(
  (var) => console.log("executing catch. " + var)
)
.finally
(
  () => console.log("executing finally.")
)

It's important to note that finally won't accept any arguments due to its nature.

Remember: although TypeScript transpiles correctly and understands your code, always verify if your JS engine supports Promise.finally. In my case, using NodeJs 8.x resulted in non-executable JS since Promise.Finally is only supported from Node 10.x onwards, check this link for more details.

Answer №3

If you want to customize your TypeScript types, you can create your own d.ts file and reference it in the tsconfig.json configuration file. This way, you can contribute your custom definitions to the DefinitelyTyped repository for the benefit of others.

Update:

To extend the existing Promise class in your own d.ts file, you can make specific methods optional so as not to conflict with the original implementation. Ensure that you define the extension as an interface within your d.ts file.

Your custom d.ts file might resemble this:

declare module 'es6-promise/dist/es6-promise' {
    export interface Promise <R> {
      finally?<U>(onFinally?: () => U | Promise<U>): Promise<U>;
    }
}

With these modifications, everything should function correctly...

I have provided an example project to showcase this: promise-typescript-extension-demo

A pull request has been submitted to the DefinitelyTyped repository, so hopefully, it will be approved soon, allowing you to access the updated definitions from there...

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

Retrieving the row value of a checkbox in an Angular table

I'm facing a challenge where I have a table with three columns, one of which is a checkbox. Here is an image for reference: https://i.sstatic.net/4U6vP.png Here is the code snippet: <div nz-row> <nz-table nz-col nzSpan="22" [nzLoading] ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

The function "useLocation" can only be utilized within the scope of a <RouterProvider> in react-router. An Uncaught Error is thrown when trying to use useLocation() outside of a <Router>

When attempting to utilize the useLocation hook in my component, I encountered an error: import React, { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { connect } from 'react-redux'; import { ...

Having trouble locating the 'EJS' Typescript for the Express framework

After attempting to implement EJS with TypeScript, I encountered an issue where I am able to use res.send without any problems. app.set('views', path.join(__dirname, 'src/views/')); app.set('view engine', 'ejs'); ...

A guide to simulating Custom Dialog in Angular for Unit Testing with Jest

Currently, I am in the process of creating test cases for unit tests and ensuring code coverage for a method that triggers a dialog component when isEdit = 'true' which is retrieved from localStorage. The issue arises with the first test case wh ...

Utilizing Ionic to implement a conditional statement for comparing a string with information retrieved from an Observable source

I have a piece of code where I fetch data about a country as an observable. I then attempt to compare my string this.city with the this.capital that I got from the Observable. If they are not the same, I want to show a new paragraph in the HTML by changi ...

The purpose of tsconfig.json

Looking to utilize Typescript to automatically create a tsconfig.json file based on a runtime object. I'm seeking the definition for this object, similar to the example below: interface TSConfigObject { compileOnSave?: boolean; files?: string ...

How can we declare and showcase a generic object with an unspecified number and names of keys in React using TypeScript?

I am facing a challenge with objects that have a 'comments' field. While all the other fields in these different objects have the same types, the 'comment' field varies. I do not know the exact number or names of the keys that will be p ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Having difficulty integrating requireJS and Node's Require in a single TypeScript project

I currently have a TypeScript project that is intended to work with both Node and the browser. In some scripts, I'm utilizing Node's require(), while in others requireJS's require(). The structure of my project directory is as follows: myPr ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

What could be causing the delay in the execution of Redux dispatch?

When I open a file and parse it, the dispatch into redux state takes longer than anticipated. It seems like the dispatch itself is taking several hundred milliseconds more than the reducer. After opening and parsing the file, the following dispatch is mad ...

Progress Tracker: Complete all fields in the form prior to advancing

Having trouble with a form stepper that consists of 3 steps. I have included the form fields for step two below. The problem is, even if I leave some REQUIRED fields empty and click on the "Next" button, I am still able to move on to step 3. I would like t ...

NestJS RabbitMQ Microservice Integration

Currently, I am attempting to establish a connection to a Rabbit MQ docker container through NestJS microservice. The setup involves running it using vagrant. Unfortunately, I keep encountering the following error: [1601171008162] ERROR (32761 on local): D ...

SolidJS does not support reactivity for arrays of objects

I've been scratching my head trying to figure out why this code isn't working as expected. I'm simply updating an object and expecting it to be refreshed in the DOM, but for some reason, that's not happening. The console log confirms th ...

Frontend Angular Posting Data to Server

https://i.sstatic.net/6dcPt.png https://i.sstatic.net/uFMuL.png I have two components - one is a form and the other is a dialog with a form. When I click on the dialog with the form and input data, I want to save it first in an in-memory, and then post all ...

Tips for executing "TS" code snippets using ts-node?

When referencing Solana documentation, TypeScript code snippets are commonly used. For instance, in the link provided below (the first code snippet) should be executed to return a value: I attempted to execute the initial snippet using: ts-node file.ts, h ...

When converting HTML to PDF, the font size appears too small when printing the document

var opt = { margin: 1, filename: '1099PdfData.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2 }, jsPDF: { unit: 'in', format: a0, orientation: 'l'} }; I am utilizing these settings to convert ...

Using TypeScript to patiently wait for an observable or promise to complete before returning an observable

As a newcomer to TypeScript & RxJS, my goal is to return an Observable once another Observable has completed: public myObservable = () : Observable<boolean> => { console.log('Retrieving the token from the database'); return ...

Issue: The 'draggable' property is not found on the 'JQuery<HTMLElement>' type

When using Angular 2 and Typescript in conjunction with JQuery and JQueryUI, I encountered the following error: Property 'draggable' does not exist on type 'JQuery<HTMLElement>' I am aware that .draggable() is a function that rel ...