[英]Typescript: use ReturnType of array of functions (edited)
我正在嘗試輸入以下 function:
function foo(input, modifier, merge) {
return merge(...modifier.map(m => m(input)));
}
目標是為merge
function 的參數提供正確的類型。
語境:
modifier
是 function 的數組,具有typeof input
類型的單個參數和每個 function 的不同返回類型merge
是一個function,它有modifier.length
參數,在position n處的參數與function的返回類型具有相同的類型)值modifier[n]
如何才能做到這一點?
可以使用對象( Record<K,V>
):
// for Functions (here type Func)
type Func = () => any;
// a mapping of a string key to an function can be created
type FuncMap = Record<string, Func>;
// for this mapping you can create a mapping to the return types of each function
type ReturnTypeMap<T extends FuncMap> = { [K in keyof T]: ReturnType<T[K]> }
基於 position 而不是 object 密鑰的 arrays 是否也可以進行類似的操作?
這是我嘗試輸入 function,但我不知道如何將 ReturnType 與 arrays 結合使用:
function foo<I, M extends Array<(input: I) => any>, O>(
input: I,
modifier: M,
merge: (...args: ReturnType<M>) => O
// ^^^^^^^^^^^^^ this is not working, since relation to each item is missing
): O {
return merge(...modifier.map(m => m(input)));
}
這樣做我認為:
type ExtractReturnTypes<T extends readonly ((i: any) => any)[]> = [
... {
[K in keyof T]: T[K] extends ((i: any) => infer R) ? R : never
}
];
function foo<I, M extends readonly ((i: I) => any)[], O>(
input: I,
modifiers: M,
merge: (...args: ExtractReturnTypes<M>) => O
) {}
foo(
1,
[(i: number) => 5, (i: number) => 'b' as const] as const,
// a has type: number
// b has type: 'b'
(a, b) => 'test'
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.