I am currently working on a way to terminate my async
method call in Typescript.
In order to achieve this, I decided to create a new type of Promise that extends from the standard Promise
:
class CustomPromise<T> extends Promise<T>{
private abortFunction: () => void;
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void, abortFunction: () => void) {
super(executor);
this.abortFunction = abortFunction;
}
//terminate the operation
public cancel() {
if (this.abortFunction) {
this.abortFunction();
}
}
}
However, when attempting to implement it like so:
async uploadFile<T>(file: File): CustomPromise<T> { ... }
I encounter the following error:
Error Build:Type 'typeof CustomPromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
If I specify the type and return the CustomPromise
, as shown below, it compiles successfully:
async uploadFile<T>(file: File): Promise<T> {
...
return CustomPromise(...);
}
What am I missing here? I have noticed that in ES6 you can subclass the Promise
(refer to stackoverflow question), which makes me believe it should be possible in TypeScript too.
This project uses TypeScript version 2.1 with es5 targeting.