One function I've been working on is called time
const time = <T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T> => {
return new Promise(async (resolve, reject) => {
const timer = setTimeout(() => reject(`Error: ${fn.name} timed out`), ms)
try {
resolve(await fn.bind(thisArg)(...args))
} catch(err) {
reject(err)
} finally {
clearTimeout(timer)
}
})
}
I'm exploring ways to avoid using the type any
for the arguments in ...args
. My goal is to connect the argument types of ...args
in the fn
function signature (
fn: (...args: any[]) => Promise<T>
) with the argument types of ...args
in the time
function. These should ideally be linked by a generic type. Initially, I considered:
const time = <T, U>(fn: (...args: U[]) => Promise<T>, ...args: U[]): Promise<T>
However, this approach seems flawed as not all arguments will have the same type. Instead, whatever type is assigned to ...args
in the fn
function's signature should also apply to the second parameter ...args
in the time
function.