Skip to content

Commit 03d2147

Browse files
Add strong typing of .opts() using generics (#1539)
Co-authored-by: tyankatsu <[email protected]> Co-authored-by: tyankatsu <[email protected]>
1 parent f9fe294 commit 03d2147

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

typings/index.d.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -483,8 +483,8 @@ export class Command {
483483
*
484484
* @returns `this` command for chaining
485485
*/
486-
storeOptionsAsProperties(): this & OptionValues;
487-
storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;
486+
storeOptionsAsProperties<T extends OptionValues>(): this & T;
487+
storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;
488488
storeOptionsAsProperties(storeAsProperties?: boolean): this;
489489

490490
/**
@@ -594,7 +594,7 @@ export class Command {
594594
/**
595595
* Return an object containing options as key-value pairs
596596
*/
597-
opts(): OptionValues;
597+
opts<T extends OptionValues>(): T;
598598

599599
/**
600600
* Set the description.

typings/index.test-d.ts

+9
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@ expectType<commander.OptionValues>(opts);
196196
expectType(opts.foo);
197197
expectType(opts['bar']);
198198

199+
// opts with generics
200+
interface MyCheeseOption {
201+
cheese: string;
202+
}
203+
const myCheeseOption = program.opts<MyCheeseOption>();
204+
expectType<string>(myCheeseOption.cheese);
205+
// @ts-expect-error Check that options strongly typed and does not allow arbitrary properties
206+
expectType(myCheeseOption.foo);
207+
199208
// description
200209
expectType<commander.Command>(program.description('my description'));
201210
expectType<string>(program.description());

0 commit comments

Comments
 (0)