Is there a way to create a Deferred promise that extends Promise while maintaining type-safe usage in scenarios where a typical Promise is expected?
Here's one possible implementation:
export class CustomDeferred<T> extends Promise<T> {
public _resolveSelf;
public _rejectSelf;
constructor() {
super(
(resolve, reject) =>
{
this._resolveSelf = resolve;
this._rejectSelf = reject;
}
)
}
public resolve(val:T) { this._resolveSelf(val); }
public reject(reason:any) { this._rejectSelf(reason); }
}
However, using this implementation may lead to a TypeError: _this is undefined
error.
When looking at the Typescript playground example, it becomes apparent that the compiled javascript code has some quirks. In line 15, properties of _this
are being assigned even before its declaration.