Push
问题描述
在类型系统里实现通用的 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, U]。