需求:在类型系统里实现 JavaScript 内置的 Array.concat 方法,这个类型接受两个参数,返回的新数组类型应该按照输入参数从左到右的顺序合并为一个新的数组。
type Concat<T extends any[], U extends any[]> = any
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Concat<[], []>, []>>,
Expect<Equal<Concat<[], [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']>>,
]
先用js的思路写一遍:
- 返回一个数组
- 对数组进行解构赋值
function concatArr(...arg){
return [...arg[0],...arg[1]];
}
再想想ts怎么写:
- 返回一个数组? √
- 对数组进行解构赋值?√
type Concat<T extends any[], U extends any[]> = [...T,...U]
题目链接:
https://github.com/type-challenges/type-challenges/blob/main/questions/00533-easy-concat/README.zh-CN.mdhttps://github.com/type-challenges/type-challenges/blob/main/questions/00533-easy-concat/README.zh-CN.md
|