題目
中文
實現一個像 Lodash.without 函數一樣的泛型 Without<T, U>,它接收數組類型的 T 和數字或數組類型的 U 爲參數,會返回一個去除 U 中元素的數組 T。
例如:
type Res = Without<[1, 2], 1>; // expected to be [2]
type Res1 = Without<[1, 2, 4, 1, 5], [1, 2]>; // expected to be [4, 5]
type Res2 = Without<[2, 3, 2, 3, 2, 3, 2, 3], [2, 3]>; // expected to be []
English
Implement the type version of Lodash.without, Without<T, U> takes an Array T, number or array U and returns an Array without the elements of U.
type Res = Without<[1, 2], 1>; // expected to be [2]
type Res1 = Without<[1, 2, 4, 1, 5], [1, 2]>; // expected to be [4, 5]
type Res2 = Without<[2, 3, 2, 3, 2, 3, 2, 3], [2, 3]>; // expected to be []
答案
type Without<T extends any[], U extends any[] | number> = U extends number
? Without<T, [U]>
: T extends [infer L, ...infer R]
? [
...(U extends [infer UL, ...infer UR]
? L extends UL
? []
: Without<[L], UR>
: [L]),
...Without<R, U>
]
: [];