Concat
问题描述
在类型系统里实现 JavaScript 内置的 Array.concat 方法,这个类型接受两个参数,返回的新数组类型应该按照输入参数从左到右的顺序合并为一个新的数组。
例如:
type Result = Concat<[1], [2]> // expected to be [1, 2]
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
const tuple = [1] as const
type cases = [Expect<Equal<Concat<[], []>, []>>, Expect<Equal<Concat<[], [1]>, [1]>>, Expect<Equal<Concat<typeof tuple, typeof tuple>, [1, 1]>>, Expect<Equal<Concat<[1, 2], [3, 4]>, [1, 2, 3, 4]>>, Expect<Equal<Concat<['1', 2, '3'], [false, boolean, '4']>, ['1', 2, '3', false, boolean, '4']>>]
// @ts-expect-error
type error = Concat<null, undefined>
// ============= Your Code Here =============
// 答案
type Concat<T extends readonly unknown[], U extends readonly unknown[]> = [...T, ...U]
简单题,首先还是需要约束泛型的类型,T extends readonly unknown[] 或者 T extends readonly any[] 都可以,二者的区别在于 unknown 在实际使用时需要判断具体的数据类型是什么,这里使用 readonly 是因为 const tuple = [1] as const 后, tuple 的类型就是只读类型 const tuple: readonly [1] 所以 typeof tuple 得到的就是只读的类型,[...T, ...U],数组的拓展运算符对泛型也同样有效。