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
View on GitHubts
type Flipped = FlipArguments<(arg0: string, arg1: number, arg2: boolean) => void>// (arg0: boolean, arg1: number, arg2: string) => void
起点
ts
/* _____________ Your Code Here _____________ */typeFlipArguments <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeFlipArguments <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// attention: 虽然never可以解构, 例如[...never], 变成一个空数组, 但是如果条件判断表达式中false下返回的是nevertypeReverse <T extends any[]> =T extends [inferF , ...inferRest ]? [...Reverse <Rest >,F ]: [];typeFlipArguments <T > =T extends (...args : inferArgs ) => inferR ? (...args :Reverse <Args >) =>R : never;
ts
// attention: 虽然never可以解构, 例如[...never], 变成一个空数组, 但是如果条件判断表达式中false下返回的是nevertypeReverse <T extends any[]> =T extends [inferF , ...inferRest ]? [...Reverse <Rest >,F ]: [];typeFlipArguments <T > =T extends (...args : inferArgs ) => inferR ? (...args :Reverse <Args >) =>R : never;