題目
中文
實現 lodash 中_.flip
方法的類型版本
FlipArguments<T>
類型接收泛型參數 T 並返回一個函數類型, 且此函數類型有和 T 相同的返回類型但其參數的順序是倒過來的
English
Implement the type version of lodash's _.flip
.
Type FlipArguments<T>
requires function type T
and returns a new function type which has the same return type of T but reversed parameters.
For example:
type Flipped = FlipArguments<
(arg0: string, arg1: number, arg2: boolean) => void
>;
// (arg0: boolean, arg1: number, arg2: string) => void
答案
type FlipArray<T extends any[]> = T extends [...infer L, infer R]
? [R, ...FlipArray<L>]
: T;
type FlipArguments<T extends Function> = T extends (
...a: infer R
) => infer TReturn
? (...a: FlipArray<R>) => TReturn
: never;