我无法将那段代码从 Javascript 转换为 Typescript。
问题是转换 ...spread 运算符。
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
尝试转换为 TS: 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:扩展参数必须具有元组类型或传递给休息参数。 如果我改变
next = calculateCombinationsTS(next, ...rest);
至 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' ]
]
最佳答案
有两个问题:
...rest: any[][]
. TypeScript 没有提示这一点,因为您可以将数组用于 any
。 ,但它更准确地反射(reflect)了您正在做的事情。calculateCombinationsTS(next, ...more);
将传递 next
的参数到函数,即使您检查了 rest.length
所以你知道它会的。您需要使用两个离散参数调用该函数,然后(可选)扩展一个数组。您可以通过从 rest
中获取第一个元素来解决此问题。参数并显式传递:if (rest.length) {
const [first, ...more] = rest;
next = calculateCombinationsTS(next, first, ...more);
}
从理论上讲,这可能会增加开销。在实践中,我怀疑开销将得到充分优化,不会成为问题。或者,因为你 了解调用是正确的(因为您知道
rest
中至少有一个元素),您可以使用 @ts-ignore
来消除错误。 ,但我尽量避免那些我可以。解决这两个问题的完整功能:
function calculateCombinationsTS(first: any[], next: any[], ...rest: any[][]) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^
if (rest.length) {
const [first, ...more] = rest; // ***
next = calculateCombinationsTS(next, first, ...more); // ***
}
return first.flatMap((a) => next.map((b) => [a, b].flat()));
}
Runnable playground example从您的示例中生成 72 种组合
关于javascript - 从 javascript t typescript 函数转换扩展运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73258461/