【问题标题】:Reference to ChildProcess class for TypeScript types对 TypeScript 类型的 ChildProcess 类的引用
【发布时间】:2017-07-09 07:12:48
【问题描述】:

我有一个简单的模块,它导出一个返回ChildProcess 实例的函数。问题是我不知道如何添加返回类型信息,因为我不知道如何获取对ChildProcess类的引用。

//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')
        })
    });

};

如果您查看 Node.js 文档,它会说 cp.spawn() 返回 ChildProcess 类的实例。

如果你看这里: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/index.d.ts

我们看到 ChildProcess 类的类型定义: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/index.d.ts#L1599

但是,我很困惑如何在我的 TypeScript 代码中引用它。

我不认为我应该导入 @types/node,因为这应该是一个 devDependency。

我该怎么办?

我需要做类似的事情:

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

}

【问题讨论】:

    标签: javascript node.js typescript typescript2.0


    【解决方案1】:

    对我来说,它改变了

    import { spawn } from 'child_process';
    

    import { ChildProcess, spawn } from 'child_process';
    

    这消除了错误:

    错误 TS4023:导出的变量“readGitTags”具有或正在使用来自外部模块“child_process”的名称“ChildProcess”,但无法命名。

    【讨论】:

      【解决方案2】:

      看起来ChildProcess 位于child_process 模块下,因此您应该可以在现有导入中引用它:

      import * as cp from 'child_process';
      
      export = function($commands: Array<string>, args?: Array<string>): cp.ChildProcess {
        //...
      }
      

      【讨论】:

      • 知道了,仍然不确定这是如何工作的,但应该可以,让我验证一下
      猜你喜欢
      • 1970-01-01
      • 2017-06-11
      • 2018-01-16
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2016-05-21
      • 2014-08-18
      相关资源
      最近更新 更多