How can I use commander (npm) with TypeScript?

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have the following code on my app:

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

Then I try to access:

commander.user 

But I get an error (commander.d.ts from DefinitelyTyped):

user does not exist on type IExportedCommand 

I tried adding this

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

But I still get the error. How can I fix this?

回答1:

Create a file commander-expansion.d.ts with the following :

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

Tip

Because I did something like this recently, recommend --auth user:password. Saves you dealing with user missing username or password. But prevents using : as a password property

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



回答2:

You can also do:

npm install --save @types/commander 


回答3:

You can keep the Typescript interface within the same file.

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

After you can define this interface to a variable after running the program.parse function.

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

I hope this helps!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!