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]

验证

import type { Equal, Expect } from '~/tc-utils'
type Push<T extends any[], U> = [...T, U]

// ---cut---
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]>>,
]

参考