Enhance ES6 Promises with TypeScript overrides using Bluebird

I am encountering a challenge with a Node.js library that utilizes promises, specifically TypeScript declarations using ES6 Promise. Interestingly, this library can be adjusted to work with any promise library, such as Bluebird.

The issue lies in making the Bluebird promise interface accessible at a declarative level without modifying the library itself. Is there a method to communicate to the compiler that a different Promise protocol is being used?

Naturally, altering the library directly would resolve this dilemma effortlessly. However, that option is not viable in this scenario.

To provide insight into the nature of this library, consider the following simplistic interface example:

interface Protocol {
    methodName(param1:string, param2:number):Promise<Object[]>
}

This interface complexity is then amplified by a factor of 1000.

Creating a mock protocol in a separate file will not suffice. The key is determining how to specify to the compiler that the default ES6 Promise should be replaced with the Bluebird TypeScript version.

Answer №1

If you want to modify the Promise type, one way to do it is by using a union. You can find more information on union types here.

While this approach works, it is not recommended

import Bluebird from 'bluebird';

type Promise = Promise | Bluebird;

As suggested in the comment by @Paarth, a better way would be to typecast your Bluebird promise to an ES6 Promise.

This is the preferred method

If you have a third-party library with a structure like:

interface Protocol {
    methodName(param1:string, param2:number):Promise<Object[]>
}

You could use it in the following way:

import Bluebird from 'bluebird';

class Http implements Protocol {
  methodName(url: string, payload: number): Promise<Object[]> {
    return <Promise<Object[]>>new Bluebird((resolve, reject) => {

      // Perform necessary actions with the url and payload

      resolve([{ data: 'Done' }]);
    });
  }
}

let http = new Http();

http.methodName('//get-some-data', 10);

Note: This code snippet has not been tested through compilation due to lack of environment setup, and issues with the Typescript compiler in jsbin

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 approach to restructuring route endpoints into an ORM framework?

As a newcomer to Angular, I find myself uncertain about what exactly qualifies as an endpoint and how it can be transformed into ORM. My current understanding suggests that an endpoint is where data is retrieved from a server, whether it's through an ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Creating a type for React onSubmit event using Typescript

I am encountering difficulties with creating an onSubmit function and assigning it a type. Regardless of what I try to assign on the first line where the function type is typically set, I consistently receive an error message, even when using 'any&ap ...

How to target a single TypeScript file in a React project that does not use TypeScript for compilation

I created a ReactJS application using the following command: $ npx create-react-app react-app-vanilla This app includes the following files: /.gitignore /README.md /package.json /public/favicon.ico /public/index.html /public/logo192.png /public/logo512.pn ...

Encountering an error with MaterialUI (MUI) after setting up webpack server, as getUtilityClass function is not recognized

My project encountered an error upon startup, displaying a Browser Runtime Error after I added webpack to the configuration. Here is a snippet of the webpack config file I used: const webpack = require('webpack'); const path = require('path& ...

Using TypeScript with generic parameters allows for flexibility while still being able to verify if a specific property is present

I am in the process of gradually converting a large SvelteKit application to TypeScript, focusing on refining the API layer. Currently, I am grappling with a function that has two generics: // Function that either performs a POST or a PUT export function s ...

Transmitting information to the main Vue class component

I'm facing an issue with a Vue component that I've defined using Vue class components. Here is the code snippet: @Component export default class MyComponent extends Vue { value = 0; } My requirement is to create multiple instances of this comp ...

using the ts-migrate-mongoose package for migrating MongoDB

I'm currently working on a NestJS application and using ts-migrate-mongoose for database migration. The issue I'm facing is related to importing a user schema from outside of the migration folder (which is located in the root folder by default). ...

Adjusting the hue of a mat-form ripple based on certain conditions

I am currently developing an angular application and using mat-form-field in the following manner. <mat-form-field appearance="fill"> <mat-label id="title">{{ title }} </mat-label> <input formControlName ...

Async and Await with Typescript

After searching extensively, I couldn't find a similar issue. I am working with Ionic 4 in Angular 7 along with Typescript 3.16. I have multiple 'TimeSpan' values that I need to retrieve using a function from the HTML like so: <ion-input ...

TypeScript's type hinting functionality is reminiscent of the way `document.createElement` works

In my project, I am in the process of developing a custom DOM with unique nodes. I want to create a method similar to createElement which will take the nodeName as an argument and return an instance of the corresponding Node. import { Node } from "./t ...

Is it possible for VSCode to automatically generate callback method scaffolding for TypeScript?

When working in VS + C#, typing += to an event automatically generates the event handler method scaffolding with the correct argument/return types. In TypeScript, is it possible for VS Code to offer similar functionality? For instance, take a look at the ...

A guide on accessing appsettings.json file configuration in Angular 10

I'm currently working on an Angular 10 web application and I am looking to access the configurations in the appsettings.json file from the Angular Home component. Below is the content of the appsettings.json file that I need to retrieve: "Appli ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...

Tips for circumventing if statements in TypeScript-ReactJS?

I currently have various action checks in place to perform different functions. Essentially, I am using if and else conditions to determine the action type and execute the corresponding functionality as shown below: public onMessage = (messageEvent) => ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

What causes the "This expression is not callable..." errors to occur in TypeScript and React JS?

As a newcomer to typescript, I am unsure why I am encountering this error while working with my data list array: const { data: CUData = { cu: [] as Array<CuType> }, } = useGetCUQuery(); let CUDataArray = CUData && CUData.cu ? CUDat ...

Tips for distributing a Vue plugin on NPM

I developed a straightforward plugin for Voca.js using Typescript. The source code can be found here. index.ts import VueVoca from './vue-voca'; export { VueVoca }; vue-voca.ts import vue from 'vue'; export default { install( ...

What is the process for displaying an image within a content-editable field?

I am in the process of developing a Rich Text Editor using Angular and TypeScript, with a contenteditable div. Successfully stored an image in the database (PouchDB) as a Base-64-encoded string. This is how it looks in plain text: <img src="data ...