5
votes

I have this simple module, which exports a function which returns an instance of ChildProcess. The problem is that I don't know how to add the return type information, because I don't know how to get a reference to the ChildProcess class.

//core
import * as cp from 'child_process';
import * as path from 'path';

//project
const run = path.resolve(__dirname +'/lib/run.sh');

export = function($commands: Array<string>, args?: Array<string>) {

    const commands = $commands.map(function(c){
          return String(c).trim();
    });

    return cp.spawn(run, (args || []), {
        env: Object.assign({}, process.env, {
            GENERIC_SUBSHELL_COMMANDS: commands.join('\n')
        })
    });

};

if you look at the Node.js docs, it says cp.spawn() returns an instance of the ChildProcess class.

If you look here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/index.d.ts

we see the type definition for the ChildProcess class: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/index.d.ts#L1599

However, I am confused how to reference this in my TypeScript code.

I don't think I am expected to import @types/node since this is supposed to be a devDependency.

What am I supposed to do?

I need to do something like:

export = function($commands: Array<string>, args?: Array<string>): ChildProcess {

}
2

2 Answers

5
votes

It looks like ChildProcess is under the child_process module, so you should be able to reference it with your existing import:

import * as cp from 'child_process';

export = function($commands: Array<string>, args?: Array<string>): cp.ChildProcess {
  //...
}
4
votes

For me it worked to change

import { spawn } from 'child_process';

to

import { ChildProcess, spawn } from 'child_process';

This got rid of the error:

error TS4023: Exported variable 'readGitTags' has or is using name 'ChildProcess' from external module "child_process" but cannot be named.