Thursday, 4 May 2017

Use commander in typescript

I try to use commander in typescript and I could like to give a proper type to my cli. So I start with this code:

import * as program from "commander";

const cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

But I get this error:

example.ts(9,17): error TS2339: Property 'debug' does not exist on type 'Command'.

So I tried to add an interface, as documented here:

import * as program from "commander";

interface InterfaceCLI extends commander.Command {
  debug?: boolean;
}

const cli: InterfaceCLI = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

and I get this error:

example.ts(3,32): error TS2503: Cannot find namespace 'commander'.

From what I understand, cli is actually a class of type commander.Command So I tried to add a class:

import * as program from "commander";

class Cli extends program.Command {
    public debug: boolean;
}

const cli: Cli = program
  .version("1.0.0")
  .usage("[options]")
  .option("-d, --debug", "activate more debug messages. Can be set by env var DEBUG.", false)
  .parse(process.argv);

console.log(cli.debug)

Which gives me this error:

example.ts(7,7): error TS2322: Type 'Command' is not assignable to type 'Cli'.
  Property 'debug' is missing in type 'Command'.

I don't know how to add a property to the Command class, either in my file or in a new .d.ts file.



via Louis Roché

No comments:

Post a Comment