diff --git a/index.js b/index.js index ec9887905..3eff059d1 100644 --- a/index.js +++ b/index.js @@ -1719,6 +1719,19 @@ class Command extends EventEmitter { return this._optionValues; }; + /** + * Return an object containing global options as key-value pairs, from parent command(s). + * + * @return {Object} + */ + globalOpts() { + const result = {}; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + Object.assign(result, parentCmd.opts()); + } + return result; + } + /** * Internal bottleneck for handling of parsing errors. * diff --git a/typings/index.d.ts b/typings/index.d.ts index 6fe954083..6ec368878 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -481,6 +481,11 @@ declare namespace commander { */ opts(): OptionValues; + /** + * Return an object containing global options as key-value pairs, from parent command(s). + */ + globalOpts(): OptionValues; + /** * Set the description. * diff --git a/typings/index.test-d.ts b/typings/index.test-d.ts index 061cf4bb6..e68ac0da6 100644 --- a/typings/index.test-d.ts +++ b/typings/index.test-d.ts @@ -171,6 +171,12 @@ expectType(opts); expectType(opts.foo); expectType(opts['bar']); +// globalOpts +const globalOpts = program.globalOpts(); +expectType(globalOpts); +expectType(globalOpts.foo); +expectType(globalOpts['bar']); + // description expectType(program.description('my description')); expectType(program.description());