What are the steps to integrating the PromiseLike interface?

I have been trying to implement an auto-commit process with support for thenables. However, I am facing difficulty resolving a type error that was raised during the last attempt:

type JobResolve = () => void

export class Job implements PromiseLike<JobResolve> {
  public then<TResult1 = JobResolve>(onfulfilled?: ((value: JobResolve) => (PromiseLike<TResult1> | TResult1)) | undefined | null): PromiseLike<TResult1> {
    const done = () => {}
    if (typeof onfulfilled === 'function') {
      const thenable = Promise.resolve(onfulfilled(done))
      done()
      return thenable
    } else {
      // Error occurs here!
      // TS2322: '() => void' is assignable to the constraint of type 'TResult1', but 'TResult1' could be instantiated with a different subtype of constraint '{}'.
      return Promise.resolve(done)
    }
  }
}

Any suggestions on how to resolve this issue without using Promise.resolve(done as any)?

Answer №1

Your else statement reveals a flaw in the definition of PromiseLike. Check out an interesting example here.

async function f() {
    let t: {a: string} = await Promise.resolve(1).then<{a: string}>();
    console.log(t, t.a, typeof t, typeof t.a);
}
f();

The variable t is identified as type number, not object, but the type system mistakenly interprets it as an object.

If your goal is to ensure compatibility with Promise, it may be more effective to explicitly cast the returned value to the desired return type:

    return Promise.resolve(done) as PromiseLike<TResult1>

Alternatively, consider throwing an exception for increased safety.

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

Is it possible for ngModelChange to function with a custom form control?

Suppose I want to create a custom form control. Is it possible to achieve this? <custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control> I've successfully implemented [(ngModel)] with all th ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

When using VSCode, Prettier, and TSLint together, enabling the 'formatOnSave' option can interfere with the automatic

As I develop React applications using TypeScript in VSCode, I rely on tools like prettier and TSLint to maintain clean code. In some recent projects, I've noticed that when I save my files, prettier disrupts the automatic sorting of imports: Before ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

Breaking down type arguments in function declarations in TypeScript

Exploring a function that reverses a pair, I am seeking to define aliases for both the input and output in a way that can be utilized within the function itself and its type signature. function reverse<A, B>([a, b]: [A, B]): [B, A] { return [b, a] ...

Leveraging asynchronous operations in Angular can greatly enhance the performance and

Upon clicking a button, my save_data method is triggered. This method includes a code snippet shown below: save_recording(){ let formData = new FormData(); formData.append("id", id); const transcript_arr = []; const confidence_arr = []; const ...

The challenge of validating in Typescript and utilizing type inference

I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes): interface Variable { someMethod: () => void } const validateVariable(variable: Variable | undefined) { ...

Error encountered: When setting up the pre-commit hook for the monorepo, a parsing error occurred stating that the `parserOptions.project` has been configured for the @typescript-eslint

We recently transitioned to a monorepo structure and are currently in the process of setting everything up. Our setup involves TypeScript, ESLint, and Prettier. Here's an overview of our project structure: root - common - folder_a - file_a ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

With each click on "add to cart," a duplicate of the component will appear

Can you help me achieve a functionality where every time I click on "addCart", a new instance of the same component (another Bets>Example Number</Bets> const newBet: React.FC = () => { const [getAddCart, setGetAddCart] = useState([ <Be ...

Parse the local JSON file and convert it into an array that conforms to an

My goal is to extract data from a local JSON file and store it in an array of InputData type objects. The JSON contains multiple entries, each following the structure of InputData. I attempted to achieve this with the code snippet below. The issue arises ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

Looking for a way to make certain pages in Vue3 accessible without authentication using KeyCloak-js

Currently, I am integrating keycloak-js adapter into a Vue 3 Application. The challenge I am facing is with the system's public pages, which prevent me from calling Keycloak immediately. Even though I have set up a button to trigger the login page, th ...

Can you explain the concept of static in Typescript?

Exploring the distinctions between the static and instance sides of classes is addressed in the Typescript documentation on this page. The static and instance sides of classes: understanding the difference In object-oriented programming languages like ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Determine the second parameter of a TypeScript function based on the first parameter

Can a function argument be inferred from another argument? I'm interested in inferring the 2nd argument based on the inference of the 1st argument. The current code can be found on GitHub at slickEventHandler.interface.ts and appears as follows: expo ...