简体   繁体   English

如何自动继承函数参数和返回类型?

[英]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 内置类型ParametersReturnType使返回的函数具有与原始函数相同的参数和返回类型:

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.

相关问题 检查泛型函数参数中的类型并返回此参数的对象字面量类型 - Check types in argument of generic function and return object literal type of this argument 返回参数类型为传入 function 参数值的函数的 object - Return object of functions with argument types of incoming function argument values 如何让函数继承返回函数的返回类型? - How to make a function inherit the return type of the returned function? 基于参数的 Typescript 返回类型,类型不是函数重载 - Typescript return type based on argument with types not function overloading Function 返回从数组参数中输入的键定义的选择类型 - Function to return picked types defined from the keys entered in array argument 如何更改 function 以接受不同类型作为参数 - How change a function to accept different types as argument 如何从作为参数传递的函数中提取参数的类型? - How to extract the types of argument from a function that was passed as argument? 如何在TypeScript中为函数参数设置参数名称和类型? - How do I set argument names and types for a function argument in TypeScript? 如何将具有多种类型的参数作为参数传递给 Typescript 中的函数? - How to pass an argument with multiple types as an argument to a function in Typescript? Typescript - 当参数为联合时,从参数属性继承返回类型 - Typescript - inherit return type from the argument property when argument is union
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM