我无法将那段JavaScript代码转换为TypeScript。
问题在于如何将扩展运算符...转换。
function calculateCombinations(first, next, ...rest) {
if (rest.length) {
next = calculateCombinations(next, ...rest);
}
return first.flatMap(a => next.map(b => [a, b].flat()));
}
a1 = ['A', 'B']
a2 = ['+', '-']
a3 = ['1', '2']
a4 = ['X', 'Y', 'Z']
// Show possibile combinations
calculateCombinations(a1, a2, a3, a4); // give me an array of 24 combinations
尝试将代码转换为 TypeScript:
function calculateCombinationsTS(first: any[], next: any[], ...rest: any[]) {
if (rest.length) {
next = calculateCombinationsTS(next, ...rest);
}
return first.flatMap(a => next.map(b => [a, b].flat()));
}
TS2556:扩展参数必须具有元组类型或传递给 rest 参数。
如果我更改
next = calculateCombinationsTS(next, ...rest);
to
next = calculateCombinationsTS(next, rest);
函数给我一个错误的结果,是因为rest被传递为数组中的数组而不是参数列表。
nCombo = (a1 * a2 * a3 * a4) = 24 possibilities
[
[ 'A', '+', '1', 'X' ], [ 'A', '+', '1', 'Y' ],
[ 'A', '+', '1', 'Z' ], [ 'A', '+', '2', 'X' ],
[ 'A', '+', '2', 'Y' ], [ 'A', '+', '2', 'Z' ],
[ 'A', '-', '1', 'X' ], [ 'A', '-', '1', 'Y' ],
[ 'A', '-', '1', 'Z' ], [ 'A', '-', '2', 'X' ],
[ 'A', '-', '2', 'Y' ], [ 'A', '-', '2', 'Z' ],
[ 'B', '+', '1', 'X' ], [ 'B', '+', '1', 'Y' ],
[ 'B', '+', '1', 'Z' ], [ 'B', '+', '2', 'X' ],
[ 'B', '+', '2', 'Y' ], [ 'B', '+', '2', 'Z' ],
[ 'B', '-', '1', 'X' ], [ 'B', '-', '1', 'Y' ],
[ 'B', '-', '1', 'Z' ], [ 'B', '-', '2', 'X' ],
[ 'B', '-', '2', 'Y' ], [ 'B', '-', '2', 'Z' ]
]