跳到主要内容

Pop

介绍

实现一个泛型Pop<T>,它接受一个数组T,并返回一个由数组T的前 N-1 项(N 为数组T的长度)以相同的顺序组成的数组。

额外:同样,您也可以实现ShiftPushUnshift吗?

例如

ts
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]
ts
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]
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type Pop<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Pop<[]>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type Pop<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Pop<[3, 2, 1]>, [3, 2]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Pop<['a', 'b', 'c', 'd']>, ['a', 'b', 'c']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Pop<[]>, []>>,
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
//方案1
type Pop<T extends any[]> = T extends [...infer R, infer L] ? R : []
 
type Push<T extends any[], U> = [...T, U]
 
type Shift<T extends any[]> = T extends [infer L, ...infer R] ? R : []
 
type Unshift<T extends any[], U> = [U, ...T]
 
ts
//方案1
type Pop<T extends any[]> = T extends [...infer R, infer L] ? R : []
 
type Push<T extends any[], U> = [...T, U]
 
type Shift<T extends any[]> = T extends [infer L, ...infer R] ? R : []
 
type Unshift<T extends any[], U> = [U, ...T]
 
view more solutions