Is it viable to incorporate generics in this scenario?
Absolutely, utilizing generics here is beneficial, especially when paired with an interface type for your encapsulated promise. While not mandatory, having the interface type will greatly simplify your implementation. Let's start by defining the interface:
interface WrappedPromise<T> extends Promise<T> {
resolve(v: T): void;
reject(e: Error): void;
promise: Promise<T>;
}
You might need to make some adjustments based on your requirements. For instance, considering that a then
handler could potentially transform the fulfillment into any type, using Promise<any>
as the return type for then
makes sense.
The next step involves assigning type arguments to your function and applying a Partial
wrapper on wrappedPromise
. This approach allows you to incrementally add properties that meet the criteria set forth by the WrappedPromise
interface (finishing with a type assertion upon completion of all parts):
const wrappedPromise = function<T>(): WrappedPromise<T> {
var wrappedPromise: Partial<WrappedPromise<T>> = {},
promise = new Promise<T>(function(resolve, reject) {
wrappedPromise.resolve = resolve;
wrappedPromise.reject = reject;
});
wrappedPromise.then = promise.then.bind(promise);
wrappedPromise.catch = promise.catch.bind(promise);
wrappedPromise.promise = promise;
return wrappedPromise as WrappedPromise<T>;
};
Your specific implementation may require tweaking, but the general concept remains consistent.
Live demo available
Be sure to refer to TypeScript's definition of Promise
for additional insights and potential refinements...