题目描述
在类型系统里实现通用的 Array.push 。
例如:
type Result = Push<[1, 2], '3'> // [1, 2, '3']
题解
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
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]>>,
]
// ============= Your Code Here =============
type Push<T extends unknown[], U> = [...T, U]
使用T extends unknown[]对传入的类型参数T进行约束,确保T是一个数组类型
[...T, U]利用展开语法按顺序展开T的元素,再将元素U添加到末尾,形成新数组