2016-05-13 33 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