跳到主要内容

Reverse

介绍

实现lodash的_.flip版本 FlipArguments<T>需要函数类型T, 并且返回一个新的函数类型,其具有相同的返回类型T,但是参数是反转的

ts
type Flipped = FlipArguments<(arg0: string, arg1: number, arg2: boolean) => void>
// (arg0: boolean, arg1: number, arg2: string) => void
ts
type Flipped = FlipArguments<(arg0: string, arg1: number, arg2: boolean) => void>
// (arg0: boolean, arg1: number, arg2: string) => void
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type FlipArguments<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<FlipArguments<() => boolean>, () => boolean>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<FlipArguments<(foo: string) => number>, (foo: string) => number>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<FlipArguments<(arg0: string, arg1: number, arg2: boolean) => void>, (arg0: boolean, arg1: number, arg2: string) => void>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type FlipArguments<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<FlipArguments<() => boolean>, () => boolean>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<FlipArguments<(foo: string) => number>, (foo: string) => number>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<FlipArguments<(arg0: string, arg1: number, arg2: boolean) => void>, (arg0: boolean, arg1: number, arg2: string) => void>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// attention: 虽然never可以解构, 例如[...never], 变成一个空数组, 但是如果条件判断表达式中false下返回的是never
type Reverse<T extends any[]> = T extends [infer F, ...infer Rest]
? [...Reverse<Rest>, F]
: [];
 
 
type FlipArguments<T> = T extends (...args: infer Args) => infer R
? (...args: Reverse<Args>) => R
: never;
 
ts
// attention: 虽然never可以解构, 例如[...never], 变成一个空数组, 但是如果条件判断表达式中false下返回的是never
type Reverse<T extends any[]> = T extends [infer F, ...infer Rest]
? [...Reverse<Rest>, F]
: [];
 
 
type FlipArguments<T> = T extends (...args: infer Args) => infer R
? (...args: Reverse<Args>) => R
: never;
 
view more solutions