我如何使用TypeScript的命令(npm)?

我的应用程序上有以下代码:

import commander = require('commander'); commander .option('-u, --user [user]', 'user code') .option('-p, --pass [pass]', 'pass code') .parse(process.argv); 

然后我尝试访问:

 commander.user 

但是我得到一个错误(从DefinitelyTyped commander.d.ts):

 user does not exist on type IExportedCommand 

我试着添加这个

 interface IExportedCommand { user: string; pass: string; } 

但是我仍然得到错误。 我怎样才能解决这个问题?

使用以下commander-expansion.d.ts创build一个文件commander-expansion.d.ts

 declare namespace commander { interface IExportedCommand extends ICommand { user: string; pass: string; } } 

小费

因为我最近做了这样的事情,推荐--auth user:password 。 保存您处理用户缺less的用户名或密码。 但是防止使用:作为密码属性

¯\_(ツ)_/¯

更多: https : //github.com/alm-tools/alm/blob/master/src/server/commandLine.ts#L24

你也可以这样做:

 npm install --save @types/commander 

您可以将Typescript界面​​保留在同一个文件中。

 interface InterfaceCLI extends commander.ICommand { user?: string password?: string } 

在运行program.parse函数之后,您可以将此接口定义为variables。

 const cli: InterfaceCLI = program.parse(process.argv) console.log(cli.user, cli.password) 

我希望这有帮助!