[英]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?有什么方法可以确保
newFunction
保持与myFunction
相同的类型,但也变得异步? 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:您可以使用 Typescripts 内置类型
Parameters
和ReturnType
使返回的函数具有与原始函数相同的参数和返回类型:
function runInThread<T extends (...args: any[]) => R, U extends Parameters<T>, R = ReturnType<T>>(fn: T, options?: unknown): (...args: U) => Promise<R> {
// your implementation
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.