BrunoLM BrunoLM - 3 months ago 34
Node.js Question

How can I use commander (npm) with TypeScript?

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?

Answer

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

Comments