2016-05-13 26 views
4

我有我的应用程序下面的代码:如何使用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; 
} 

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

回答

5

具有以下创建一个文件commander-expansion.d.ts

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

提示

因为我最近做了这样的事情,建议--auth user:password。节省您处理用户缺少的用户名或密码。但是防止使用:作为密码属性

¯\_(ツ)_/¯

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

1

你可以保持在同一文件中的打字稿接口。

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

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

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

我希望这有助于!

2

你也可以这样做:

npm install --save @types/commander