题目描述
实现一个泛型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]
题解
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type cases = [
Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,
Expect<Equal<Pop<[]>, []>>,
]
// ============= Your Code Here =============
type Pop<T extends any[]> = T extends [...infer Head, unknown] ? Head : []
使用T extends unknown[]对传入的类型参数T进行约束,确保T是一个数组类型
T extends [...infer Head, unknown]:当T不为空数组时,使用infer结合展开运算符来提取除元素外的元素,并存储在Head中,返回Head
当T是空数组时,返回[]