![](/img/trans.png)
[英]Check types in argument of generic function and return object literal type of this argument
[英]How to auto inherit function argument and return types?
我正在開發一個接收函數並在單獨的工作線程上運行它的助手。 想法是向它傳遞一個函數,它返回您可以在新線程上執行時等待的異步函數。 我正在嘗試為它創建打字,但被困在以下內容中:
export type MyReturnType = [(...fnArgs: any[]) => (Promise<any>), string, () => void];
export function runInThread(fn: Function, options?: MyOptions): MyReturnType;
當我使用這個功能時,我通常會這樣做
function myFunction(value: number) {
return number * 2;
}
const [newFunction] = runInThread(myFunction)
const result = await newFunction(100);
console.log(result) // 200
有什么方法可以確保newFunction
保持與myFunction
相同的類型,但也變得異步? 它應該保留參數和返回類型。
您可以使用 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.