1

I am attempting to extend the Promise object with the following code:

class MyPromise extends Promise {
    constructor(executor) {
        super((resolve, reject) => {
            return executor(resolve, reject);
        });
    }
}

However, I am getting the following error: enter image description here

What does this error mean? How can I successfully extend Promise?

aBlaze
  • 2,436
  • 2
  • 31
  • 63

1 Answers1

3

Try this...

class MyPromise<T> extends Promise<T> {
    constructor(executor: (resolve: any, reject: any) => MyPromise<T>) {
        super((resolve, reject) => {
            return executor(resolve, reject);
        });
    }
}
Will Walsh
  • 1,799
  • 1
  • 6
  • 15
  • Why does this work? Can you please explain more? – aBlaze May 27 '21 at 01:05
  • To be honest, I am not sure why this works. I am not well versed in TypeScript. I 'derived' the answer from information here (https://stackoverflow.com/questions/43327229/typescript-subclass-extend-of-promise-does-not-refer-to-a-promise-compatible-c) and using a TypeScript sandbox. *blush* – Will Walsh May 27 '21 at 01:15
  • 1
    You do not need to wrap the executor function in a lambda. You can just pass it directly as it already fulfills the type constraints. Try just: ```constructor(executor: (resolve: any, reject: any) => MyPromise) { super(executor); }``` – Octal Feb 10 '22 at 02:35
  • You don't need to define the constructor at all. All you need is the generic T for both MyPromise and Promise. – sdgluck Sep 05 '22 at 16:06