I am to trying add a method to Function
.
The problem is that the return value dose not automaticlly inherit T.
interface Function {
Promise <T> (...args: any[]): Promise<T> ;
}
Function.prototype.Promise = async function <T> (this: Function , ...args: any[]): Promise <T> {
return new Promise <T> ((resolve, reject) => {
this(args).then((x: T) => resolve(x)).catch((e: any) => reject(e));
});
}
var test =(async()=> {
return "";
});
// this return Promise<unknown> it should return Promise<string>
test.Promise()
// this should work, but I want the above to work instead
// it should inherit the type automaticly
test.Promise<string>()
CodePudding user response:
You can capture the type of the function that was invoked using the this
parameter. You can also capture the type of the parameters and the return type to better type the resulting function.
interface Function {
Promise<TReturn, TArgs extends any[]>(this: (...a: TArgs) => Promise<TReturn>, ...a: TArgs): Promise<TReturn>;
}
Function.prototype.Promise = async function <TReturn, TArgs extends any[]>(this: (...a: TArgs) => Promise<TReturn>, ...args: TArgs): Promise<TReturn> {
return new Promise<TReturn>((resolve, reject) => {
this(...args).then((x: TReturn) => resolve(x)).catch((e: any) => reject(e));
});
}
var test = (async () => {
return "";
});
// this return Promise<unknown> it should return Promise<string>
test.Promise()