Open yunliuyan opened 1 year ago
出堆思想
type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]
type Pop<T extends any[]> = T extends [...infer args, infer U] ? args : never;
type re1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type re2 = Pop<arr2> // expected to be [3, 2]
type Pop<T extends unknown[]> = T extends [...infer U, infer P] ? U : never;
type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]
type tail1 = Pop<arr1> // expected to be ['a', 'b', 'c']
type tail2 = Pop<arr2> // expected to be [3, 2]
type Shift<T extends unknown[]> = T extends [infer U, ...infer P] ? U : never;
type arr1 = ['a', 'b', 'c', 'd']
type arr2 = [3, 2, 1]
type tail1 = Shift<arr1> // expected to be ['a']
type tail2 = Shift<arr2> // expected to be [3]
type Push<T extends unknown[], U> = [...T, U];
type arr1 = ['a', 'b', 'c'];
type arr2 = [3, 2, 1];
type tail1 = Push<arr1, 0>; // expected to be ['a', 'b', 'c', 0]
type tail2 = Push<arr2, 0>; // expected to be [3, 2, 1, 0]
type Unshift<T extends unknown[], U> = [U, ...T];
type arr1 = ['a', 'b', 'c'];
type arr2 = [3, 2, 1];
type tail1 = Unshift<arr1, 0>; // expected to be [0, 'a', 'b', 'c']
type tail2 = Unshift<arr2, 4>; // expected to be [4, 3, 2, 1]
type Pop<T extends unknown[]> = T extends [...infer args, infer P] ? args : never;
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]
// 实现一个通用Pop<T>,它接受一个数组T并返回一个没有最后一个元素的数组。
type Pop<T> = T extends [... infer P, infer last] ? P : never;
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]
type popArr1 = ['a', 'b', 'c', 'd']
type popArr2 = [3, 'a', 1]
type MyPop<T extends any[]> = T extends [...infer args, infer U] ? args : never;
type popRe1 = MyPop<popArr1> // expected to be ['a', 'b', 'c']
type popRe2 = MyPop<popArr2> // expected to be [3, 'a']
出堆
实现一个通用
Pop<T>
,它接受一个数组T
并返回一个没有最后一个元素的数组。例如
测试案例:
额外:同样,您也可以实现
Shift
,Push
和Unshift
吗?相关挑战