打字稿:如何键入可变参数?

时间:2020-11-05 05:00:45

标签: typescript

尝试将此函数转换为打字稿:

const runProcess = (...proc) => {
  const proc = child_process.spawn(...proc, {
    stdio: ["ignore", "pipe", "pipe"],
  });

可以做到吗?在这种特殊情况下,proc可以是单个字符串,也可以是由字符串和字符串数组组成的2元组(如何在TS中表示?)。

1 个答案:

答案 0 :(得分:3)

对于创建元组,您只需将类型按出现的顺序放在方括号内即可。 [string, string[]]string的2元组和字符串数组(string[])的类型。

由于我们正在传播runProcess的参数并将其视为数组,因此我们需要将其他参数类型(单个字符串)视为1元组[string]

我们说我们的参数proc是这两个元组之一:[string] | [string, string[]]。因此,我们知道args数组中的第一个元素始终是string,第二个元素是string[]undefined。为了调用child_process.spawn,如果没有给出第二个参数,我们想默认使用一个空数组。

该签名看起来像:

const runProcess = (...proc: [string] | [string, string[]]) => {
    const [str, arr = []] = proc;
    const child = child_process.spawn(str, arr, {
        stdio: ["ignore", "pipe", "pipe"],
    });
}

但是考虑到我们始终只处理一个或两个参数,我不确定将参数扩展为...proc是否真的有意义。为什么不只有必需的第一个参数和可选的第二个参数(默认为空数组)呢?

const runProcess = (command: string, args: string[] = []) => {
    const proc = child_process.spawn(command, args, {
        stdio: ["ignore", "pipe", "pipe"],
    });
}

Playground Link

编辑:如@Aleksey L.所建议,您可以将生成的args作为单独的字符串参数而不是作为数组传递。

const runProcess = (command: string, ...args: string[]) => {
    const proc = child_process.spawn(command, args, {
        stdio: ["ignore", "pipe", "pipe"],
    });
}

Playground Link

相关问题