Reverse
问题描述
实现类型版本的数组反转 Array.reverse
例如:
type a = Reverse<['a', 'b']> // ['b', 'a']
type b = Reverse<['a', 'b', 'c']> // ['c', 'b', 'a']
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type cases = [
Expect<Equal<Reverse<[]>, []>>,
Expect<Equal<Reverse<['a', 'b']>, ['b', 'a']>>,
Expect<Equal<Reverse<['a', 'b', 'c']>, ['c', 'b', 'a']>>,
]
type errors = [
// @ts-expect-error
Reverse<'string'>,
// @ts-expect-error
Reverse<{ key: 'value' }>,
]
// ============= Your Code Here =============
// 答案1
type Reverse<T extends any[]> = T extends [infer F, ...infer R] ? [...Reverse<R>, F] : T
// 答案2
type Reverse<T extends any[]> = T extends [...infer F, infer R] ? [R,...Reverse<F>] : T
这道题很简单,首先约束传入的泛型为数组,其次将第一位放在最后一位,再将剩余的传入当前类型递归调用,最后返回即可,也可以用相反的思路,将最后一位放在第一位,然后再将剩余的传入当前类型递归调用,最后返回。