Ilja
Ilja

Reputation: 46519

How to auto inherit function argument and return types?

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.

Upvotes: 0

Views: 99

Answers (1)

cyr_x
cyr_x

Reputation: 14257

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
}

Upvotes: 3

Related Questions