TypeScript type definition for promise.prototype.finally

jpierson picture jpierson · Mar 8, 2016 · Viewed 11.5k times · Source

I was using this ES6 Promise compatible finally implementation called promise.prototype.finally in a Node application that I want to convert to TypeScript however there are no typing available for this package that I can find on DefinitelyTyped. In these situations I've written up my own impromptu type definitions for just the subset of functionality that I need but in this case it is a library that modifies the prototype of the Promise object and I haven't encountered any conventional way to represent this in TypeScript. Any ideas?

Possibly related:

Answer

Tom Spencer picture Tom Spencer · Dec 14, 2016

Whilst the answer from Slava is correct, it only deals with the typing of the finally block. To actually incorporate the shim into your code, so you can write p.finally(() => { ... }), you need to invoke the shim.

Unfortunately the typings on DefinitelyTyped do not currently support the shim function so until this is supported, I'd advise to add the typings yourself.

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

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

The types are now available. Install with

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

In your TypeScript code, during application bootstrap, you can then call

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

This will add the finally block to the Promise prototype, allowing you to use finally as required.