[TypeScript] Type Challenges #533 - Concat

104 阅读1分钟

题目描述

在类型系统里实现 JavaScript 内置的 Array.concat 方法,这个类型接受两个参数,返回的新数组类型应该按照输入参数从左到右的顺序合并为一个新的数组。

例如:

type Result = Concat<[1], [2]> // expected to be [1, 2]

题解

// ============= Test Cases =============
import type { EqualExpect } from './test-utils'

const tuple = [1as const

type cases = [
  Expect<Equal<Concat<[], []>, []>>,
  Expect<Equal<Concat<[], [1]>, [1]>>,
  Expect<Equal<Concat<typeof tuple, typeof tuple>, [11]>>,
  Expect<Equal<Concat<[12], [34]>, [1234]>>,
  Expect<Equal<Concat<['1'2'3'], [falseboolean'4']>, ['1'2'3'falseboolean'4']>>,
]

// @ts-expect-error
type error = Concat<nullundefined>


// ============= Your Code Here =============
type Concat<T extends readonly unknown[], U extends readonly unknown[]> = [...T, ...U]

1、通过T extends readonly unknown[]U extends readonly unknown[]来约束传入的类型参数TU必须是数组类型

2、使用展开语法[...T, ...U]合并数组类型TU