I would like to create function with optional count of type parameters. For example, function accepts parameters, where each parameter is array and returns array, where nth item is random item from nth parameter:
const getRandomItems<T1, T2, T3>(...arrays: [T1[], T2[], T3[]]): [T1, T2, T3] = {
const result = []
for (const items of arrays) {
result.push(items[Math.floor(Math.random() * items.length)])
}
return result
}
const fruits = ['Apple', 'Orange', 'Banana']
const colors = ['Red', 'Green', 'Blue']
const cars = [new Car('Ferrari'), new Car('Porsche')]
// E.g. ['Apple', 'Blue', new Car('Porsche')]
getRandomItems<string, string, Car>(friuts, colors, cars)
// E.g. ['Orange', new Car('Ferrari'), 'Red']
getRandomItems<string, Car, string>(friuts, cars, colors)
This function accepts 3 parameters and returns array with 3 parameters. But can I create function, that:
- Accept any number of typed parameters, e. g.
<T1, T2, T3, T4>, - Accept same number of parameters as type parameters:
...arrays: [T1[], T2[], T3[], T4[]], - Returns array with same types as typed parameters:
[T1, T2, T3, T4]?
// Something like this:
const getRandomItems<...T>(...arrays: [...T[]]): [...T] = {
}