Typescript类型体操 - FlipArguments

题目

中文

实现 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;

在线演示

posted @ 2022-09-24 20:05  Laggage  阅读(28)  评论(0编辑  收藏  举报