实现一个泛型 Pop<T>,它接受一个数组 T,并返回一个由数组 T 的前 N-1 项(N 为数组 T 的长度)以相同的顺序组成的数组
例如:
type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]
type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]
扩展:同样,您也可以实现 Shift,Push 和 Unshift 吗?
/* _____________ 你的代码 _____________ */
type Pop<T extends readonly any[]> = T extends [...infer F, any] ? F : T
type Shift<T extends readonly any[]> = T extends [any, ...infer R] ? R : T
type Unshift<T extends readonly any[], V> = [V, ...T]
/* _____________ 测试用例 _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,
Expect<Equal<Pop<[]>, []>>,
Expect<Equal<Shift<[3, 2, 1]>, [2, 1]>>,
Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,
Expect<Equal<Shift<[]>, []>>,
Expect<Equal<Unshift<[3, 2, 1], 'xyz'>, ['xyz', 3, 2, 1]>>,
Expect<Equal<Unshift<['a', 'b', 'c', 'd'], 'xyz'>, ['xyz', 'a', 'b', 'c', 'd']>>,
Expect<Equal<Unshift<[], 'xyz'>, ['xyz']>>,
]
[[011.Push|Push]] 之前实现过