2017-05-05 16 views
2

私はtypescriptでコマンダーを使用しようとしています。私は自分のcliに適切なタイプを与えることができます。だから私は、このコードで始まる:司令官をタイプコピーで使用する

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'. 

ので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) 

と、私はこれを取得しますエラー:

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

cliは、だから私はクラスを追加しようとした実際のタイプcommander.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'. 

私は追加する方法がわかりません私のファイルまたは新しい.d.tsファイルのCommandクラスのプロパティ。あなたの最初のコードスニペットと、次の依存関係を持つ

答えて

2

、私はエラーを取得しない:

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

活字体はanyとしてcli.debugを解釈します。私は型宣言が更新されていると思います。だから、もしあなたがanyであれば、問題は解決されます。

Typescriptにタイプdebugを伝えたい場合は、基本的にはdeclaration mergingとなります。これは基本的に次のように機能します。

ただし、問題があります:program.Command is not a type but a variable。あなたがこれを行うことができますしながら、

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 { 
} 

この問題が解決できるかどうかわかりませんdかどうか。

関連する問題