Pop
介绍
实现一个泛型Pop<T>
,它接受一个数组T
,并返回一个由数组T
的前 N-1 项(N 为数组T
的长度)以相同的顺序组成的数组。
额外:同样,您也可以实现Shift
,Push
和Unshift
吗?
例如
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 GitHubts
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
/* _____________ Your Code Here _____________ */typePop <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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 <[]>, []>>,]
take the challengets
/* _____________ Your Code Here _____________ */typePop <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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 <[]>, []>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
//方案1typePop <T extends any[]> =T extends [...inferR , inferL ] ?R : []typePush <T extends any[],U > = [...T ,U ]typeShift <T extends any[]> =T extends [inferL , ...inferR ] ?R : []typeUnshift <T extends any[],U > = [U , ...T ]
ts
//方案1typePop <T extends any[]> =T extends [...inferR , inferL ] ?R : []typePush <T extends any[],U > = [...T ,U ]typeShift <T extends any[]> =T extends [inferL , ...inferR ] ?R : []typeUnshift <T extends any[],U > = [U , ...T ]