2017-02-20 49 views
2

我有這個簡單的模塊,它導出一個返回ChildProcess實例的函數。問題是我不知道如何添加返回類型信息,因爲我不知道如何獲得對ChildProcess類的引用。對TypeScript類型的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()返回子進程類的一個實例。

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

我們看到的類型定義爲子進程類: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/index.d.ts#L1599

不過,我很困惑如何在我的打字稿代碼中引用此。

我不認爲我預計導入@types/node,因爲這應該是一個devDependency。

我該怎麼辦?

我需要做的是這樣的:

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

} 

回答

3

看起來ChildProcesschild_process模塊下,所以你應該能夠與您現有的進口引用它:

import * as cp from 'child_process'; 

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

得到它,還是真的不知道這是如何工作的,但應該這樣做,讓我驗證 –

1

對我來說它努力改變

import { spawn } from 'child_process'; 

import { ChildProcess, spawn } from 'child_process'; 

這擺脫了錯誤的:

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