Concat
介绍
在类型系统里实现 JavaScript 内置的 Array.concat
方法,这个类型接受两个参数,返回的新数组类型应该按照输入参数从左到右的顺序合并为一个新的数组。
例如
ts
type Result = Concat<[1], [2]>; // expected to be [1, 2]
View on GitHubts
type Result = Concat<[1], [2]>; // expected to be [1, 2]
起点
ts
/* _____________ Your Code Here _____________ */typeConcat <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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]>>,Expect <Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Equal <Concat <['1', 2, '3'], [false, boolean, '4']>,['1', 2, '3', false, boolean, '4']>>];
take the challengetake the challengets
/* _____________ Your Code Here _____________ */typeConcat <T ,U > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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]>>,Expect <Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Equal <Concat <['1', 2, '3'], [false, boolean, '4']>,['1', 2, '3', false, boolean, '4']>>];
解决方案
Spoiler warning // Click to reveal answer
ts
typeConcat <T extends readonly unknown[],U extends readonly unknown[]> = [...T , ...U ]// 注意事项:/*** 1. unknown[] 与 any[]的区别* 2. 只读数组和数组的区别*/
ts
typeConcat <T extends readonly unknown[],U extends readonly unknown[]> = [...T , ...U ]// 注意事项:/*** 1. unknown[] 与 any[]的区别* 2. 只读数组和数组的区别*/