Typescript类型体操 - Pop
题目
中文
实现一个通用Pop<T>
,它接受一个数组T
,并返回一个由数组T
的前length-1项以相同的顺序组成的数组。
例如
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
吗?
English
Implement a generic Pop<T>
that takes an Array T
and returns an Array without it's last element.
For example
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]
Extra: Similarly, can you implement Shift
, Push
and Unshift
as well?
答案
type Pop<T extends any[]> = T extends [... infer R, infer E] ? [...R]: never;
附加题Shift
Push
Unshift
的实现
type Shift<T extends any[]> = T extends [infer L, ...infer R] ? [...R] : never;
type Unshift<T extends any[], V extends any[] = []> = [...V, ...T];
type Push<T extends any[], V extends any[] = []> = [...T, ...V];