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]

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

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];

在线演示

posted @ 2022-09-04 22:10  Laggage  阅读(56)  评论(0编辑  收藏  举报