我正在try 编写一个函数fc
,该函数接受2个对象并以完全类型安全的方式返回它们的合并版本:
const rfc = fc({ num: [1, 2, 3] }, { num: [4, 5, 6] });
// ^? { num: [1, 2, 3, 4, 5, 6] }
怎么做呢?
-
平坦
让我们try 简单地使用可变元组的TypeScript spread语法:
type t1a = [1, 2, 3] type t2a = [4, 5, 6] type ra = [...t1a, ...t2a] // ^? [1, 2, 3, 4, 5, 6] // awesome, works
让我们使用通用的类型脚本函数(在this blog的帮助下)来try 一下:
function fa<T1 extends number[], T2 extends number[]>(t1: [...T1], t2: [...T2]): [...T1, ...T2] { return [...t1, ...t2]; } const rfa = fa([1, 2, 3], [4, 5, 6]); // ^? [1, 2, 3, 4, 5, 6] // awesome, works
-
嵌套的
让我们try 在嵌套props 上传播类型:
type t1b = { num: [1, 2, 3] } type t2b = { num: [4, 5, 6] } type rtb = [...t1b['num'], ...t2b['num']] // ^? [1, 2, 3, 4, 5, 6] // awesome, works
现在使用泛型:
function fc<T1 extends { num: number[] }, T2 extends { num: number[] }>( t1: T1, t2: T2, ): { num: [...T1['num'], ...T2['num']] } { return { num: [...t1.num, ...t2.num] as any }; } const rfc = fc({ num: [1, 2, 3] }, { num: [4, 5, 6] }); // ^? {num: number[]} // why?? why not [1, 2, 3, 4, 5, 6] ??
为什么
rfc
不是我预想的[1, 2, 3, 4, 5, 6]
?