在打字稿中使用指挥官

我尝试在打字稿中使用指挥官,我想给我的气候适当的types。 所以我从这个代码开始:

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) 

但是我得到这个错误:

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

所以我试着添加一个接口,如下所述:

 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) 

我得到这个错误:

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

据我所知, cli实际上是一个typescommander.Command所以我试图添加一个类:

 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) 

这给了我这个错误:

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

我不知道如何添加属性到Command类中,无论是在我的文件中还是在一个新的.d.ts文件中。

用你的第一个代码片段和下面的依赖关系,我不会得到一个错误:

 "dependencies": { "commander": "^2.11.0" }, "devDependencies": { "@types/commander": "^2.9.1", "typescript": "^2.4.1" } 

Typescript将cli.debug解释为any 。 我猜这个types声明已经更新了。 所以,如果你any问题,问题就解决了。

如果你真的想告诉Typescript debug的types, 声明合并原则上是要走的路。 它基本上是这样工作的:

 class C { public foo: number; } interface C { bar: number; } const c = new C(); const fooBar = c.foo + c.bar; 

但是,有一个问题: program.Command不是一个types,而是一个variables 。 所以,你不能这样做:

 interface program.Command { debug: boolean; } 

而你可以做到这一点:

 function f1(): typeof program.Command { return program.Command; } type T = typeof program.Command; function f2(): T { return program.Command; } 

你既不能做到这一点:

 interface typeof program.Command { } 

也不是这样:

 type T = typeof program.Command; interface T { } 

我不知道这个问题是否可以解决。