打字稿使用带有REST运算符的通用类型

问题描述

我有这种方法可以从2个数组中创建成对的数组


function join<T,K> (arr1: T[],arr2: K[]): [T,K][]{
  const res = [];

  arr1.forEach(p => {
    arr2.forEach(n => {
      res.push([p,n])
    })
  })

  return [];
}

//I use it to create test data like this
// [["a",1],["a",2],["b",2]]
join(["a","b"],[1,2]).forEach(([char,num]) => {
  it(`should do something with ${char} and ${num}`,() => {
    //assert here
  })
})

是否有一种简单的方法可以轻松地将join函数的比例推广到两个以上的参数并保持类型检查? 也许使用rest运算符...arr和/或一些重载?

解决方法

我不确定我是否理解正确,但是如果您的数组中只有字符串和数字,则可以执行以下操作:

type customArray = (string | number)[];

const join = (args: customArray[]): void => {
   // ...
};

// Now you can pass any amount of arguments
join([['a',1],['b',2],['c,3'],['d',4]]);
,

我认为可变元组可能会有所帮助:

function join<T extends unknown[][]>(...args: T): T[] {
    const res = [];

    args[0].forEach(p => {
        args[1].forEach(n => {
            res.push([p,n])
        })
    })

    return res;
}

join2(["a","b"],[1,["a,b"],[false,true]).forEach(([char,num,str,bool]) => {

});

您可以自己编写函数的主体,但是char,num,str和bool变量的类型正确。