I am working on a helper that takes in a function and runs it on a separate worker thread. Idea is to pass it a function and it returns you async function you can await while it is being executed on a new thread. I am trying to create typing for it but am stuck at following:
export type MyReturnType = [(...fnArgs: any[]) => (Promise<any>), string, () => void];
export function runInThread(fn: Function, options?: MyOptions): MyReturnType;
When I use this function I would normally do it this way
function myFunction(value: number) {
return number * 2;
}
const [newFunction] = runInThread(myFunction)
const result = await newFunction(100);
console.log(result) // 200
Is there any way to ensure that newFunction
keeps same types as myFunction
, but also becomes async? It should keep argument and return types.
You can use Typescripts build in types Parameters
and ReturnType
to make the returned function has the same arguments and return type of the original function:
function runInThread<T extends (...args: any[]) => R, U extends Parameters<T>, R = ReturnType<T>>(fn: T, options?: unknown): (...args: U) => Promise<R> {
// your implementation
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.