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