跳到主要内容

Concat

介绍

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

ts
type Result = Concat<[1], [2]>; // expected to be [1, 2]
ts
type Result = Concat<[1], [2]>; // expected to be [1, 2]
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
type Concat<T, U> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Concat<[], []>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Concat<[], [1]>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Concat<[1, 2], [3, 4]>, [1, 2, 3, 4]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<
Equal<
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Concat<['1', 2, '3'], [false, boolean, '4']>,
['1', 2, '3', false, boolean, '4']
>
>
];
ts
/* _____________ Your Code Here _____________ */
type Concat<T, U> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Concat<[], []>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Concat<[], [1]>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Concat<[1, 2], [3, 4]>, [1, 2, 3, 4]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<
Equal<
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Concat<['1', 2, '3'], [false, boolean, '4']>,
['1', 2, '3', false, boolean, '4']
>
>
];
take the challengetake the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type Concat<T extends readonly unknown[],U extends readonly unknown[]> = [...T, ...U]
// 注意事项:
/**
* 1. unknown[] 与 any[]的区别
* 2. 只读数组和数组的区别
*/
ts
type Concat<T extends readonly unknown[],U extends readonly unknown[]> = [...T, ...U]
// 注意事项:
/**
* 1. unknown[] 与 any[]的区别
* 2. 只读数组和数组的区别
*/
view more solutions