Typescript:如何为可变参数指定类型?
尝试将此函数转换为 TypeScript:
const runProcess = (...proc) => {
const proc = child_process.spawn(...proc, {
stdio: ["ignore", "pipe", "pipe"],
});
这可以做到吗?在这种特定情况下,procs 可以是单个字符串,也可以是由一个字符串和一个字符串数组组成的二元组(在 TypeScript 中如何表示这个?)。
答案#1
要创建一个元组,你只需将类型按出现的顺序放在方括号内。[string, string[]] 是一个由 string 和字符串数组 (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"],
});
}
游乐场链接
编辑:如 @Aleksey L. 所建议的,你可以将 spawn args 作为单独的字符串参数传递,而不是作为数组。
const runProcess = (command: string, ...args: string[]) => {
const proc = child_process.spawn(command, args, {
stdio: ["ignore", "pipe", "pipe"],
});
}
游乐场链接
