Skip to content

Push

177字小于1分钟

2022-12-01

题目

Github: Push

在类型系统里实现通用的 Array.push

type Result = Push<[1, 2], '3'> // [1, 2, '3']

解题思路

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

答案

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

验证

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

参考