For creating a tuple, you just put the types inside of the square brackets in the order that they appear. [string, string[]]
is the type for a 2-tuple of a string
and an array of strings (string[]
).
Since we are spreading the arguments of runProcess
and treating it like an array, we need to treat the other argument type – a single string – as a 1-tuple [string]
.
We say that our args proc
is either one of these two tuples: [string] | [string, string[]]
. Therefore we know that the first element in the args array is always a string
and the second element is either string[]
or undefined
. In order to call child_process.spawn
, we want to default to an empty array for the second argument if none is given.
That signature looks like:
const runProcess = (...proc: [string] | [string, string[]]) => {
const [str, arr = []] = proc;
const child = child_process.spawn(str, arr, {
stdio: ["ignore", "pipe", "pipe"],
});
}
But given that we are always dealing with exactly one or two arguments, I’m not sure that it really makes sense to spread the arguments as ...proc
. Why not just have a required first argument and an optional second argument that defaults to an empty array?
const runProcess = (command: string, args: string[] = []) => {
const proc = child_process.spawn(command, args, {
stdio: ["ignore", "pipe", "pipe"],
});
}
Edit: as suggested by @Aleksey L., you can pass the spawn args
as individual string arguments rather than as an array.
const runProcess = (command: string, ...args: string[]) => {
const proc = child_process.spawn(command, args, {
stdio: ["ignore", "pipe", "pipe"],
});
}
CLICK HERE to find out more related problems solutions.