ThomasReggi
ThomasReggi

Reputation: 59345

Typing for a general promise library

I have a function that takes a promise library.

function takeLib(promiseLibrary) {

}

I'd like to type it so it has to be a class with .then and .catch methods.

I created an abstract class like this:

export abstract class PromiseLibraryAbstract {
  abstract then(...args: any[]): any
  abstract catch(...args: any[]): any
}

However I get typing issues when I try and use it:

export type PromiseLibrary = typeof PromiseLibraryAbstract

const x: PromiseLibrary = Promise

function takeLib(promiseLibrary: PromiseLibrary) {

}

takeLib(Promise)

How can I type a general class shape?

Playground

Upvotes: 0

Views: 42

Answers (2)

Dus
Dus

Reputation: 4230

I think that you have an issue with calling takeLib - you need to pass x instead of Promise.. Plus, x is of type PromiseLibraryAbstract

export abstract class PromiseLibraryAbstract {
  abstract then(...args: any[]): any
  abstract catch(...args: any[]): any
}

export type PromiseLibrary = typeof PromiseLibraryAbstract

const x: PromiseLibrary = PromiseLibraryAbstract

function takeLib(promiseLibrary: PromiseLibrary) {

}

takeLib(x)

Upvotes: 0

Aleksey L.
Aleksey L.

Reputation: 37918

You're missing constructor definition, that's why types are not compatible. You can use something similar to original Promise constructor definition:

export abstract class PromiseLibraryAbstract {
  constructor(executor: (resolve: (value?: any) => void, reject: (reason?: any) => void) => void) {

  }
  // ...
}

Playground

Upvotes: 1

Related Questions