Search code examples
node.jstypescriptchild-processspawn

How to use NodeJS child_process in typescript?


When I try to execute a child_process spawn in interactive mode node -i it works, no problem.
E.g.

node -i
> const { spawn } = require('node:child_process');
> spawn("ls", ["-lah"]);

A child process is created, everything's fine.

When I try to use child_process in typescript like

...
import spawn from "node:child_process";
...
  
spawn("ls", ["-lah"]);

it doesn't work.

VSCode highlights the last line spawn(...) with the error message

This expression is not callable.
  Type 'typeof import("node:child_process")' has no call signatures.

When I build the code I get the same message

src/main.ts:20:3 - error TS2349: This expression is not callable.
  Type 'typeof import("node:child_process")' has no call signatures.

It doesn't matter which command I try to call in spawn(...), I tried several, always the same error.
How do I use child_process in typescript correctly?


Solution

  • You still need the curly braces, or else you're importing the whole package as spawn, which isn't callable

    ...
    import { spawn } from "node:child_process";
    ...
      
    spawn("ls", ["-lah"]);