Skip to content

Unshift

175字小于1分钟

2022-12-01

题目

Github: Unshift

实现类型版本的 Array.unshift

type Result = Unshift<[1, 2], 0> // [0, 1, 2,]

解题思路

通过 泛型约束T 为数组类型,对 T 进行展开到新数组中,并将 U 合并到新数组的首位。

答案

type Unshift<T extends any[], U> = [U, ...T]

验证

type 
cases
= [
Expect
<
Equal
<
Unshift
<[], 1>, [1]>>,
Expect
<
Equal
<
Unshift
<[1, 2], 0>, [0, 1, 2]>>,
Expect
<
Equal
<
Unshift
<['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>,
]

参考