Skip to content

Commit

Permalink
BREAKING(yargs): fix InferredOptionType inference (DefinitelyTyped#52624
Browse files Browse the repository at this point in the history
)

* fix(yargs): fix type inference of InferredOptionType

* test(yargs): add test using default and demandOption together
  • Loading branch information
tasshi-me committed May 18, 2021
1 parent 3107a07 commit 293f8fa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
14 changes: 10 additions & 4 deletions types/yargs/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,14 +781,20 @@ declare namespace yargs {
type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;

type InferredOptionType<O extends Options | PositionalOptions> =
O extends (
| { required: string | true }
| { require: string | true }
| { demand: string | true }
| { demandOption: string | true }
) ?
Exclude<InferredOptionTypeInner<O>, undefined> :
InferredOptionTypeInner<O>;

type InferredOptionTypeInner<O extends Options | PositionalOptions> =
O extends { default: any, coerce: (arg: any) => infer T } ? T :
O extends { default: infer D } ? D :
O extends { type: "count" } ? number :
O extends { count: true } ? number :
O extends { required: string | true } ? RequiredOptionType<O> :
O extends { require: string | true } ? RequiredOptionType<O> :
O extends { demand: string | true } ? RequiredOptionType<O> :
O extends { demandOption: string | true } ? RequiredOptionType<O> :
RequiredOptionType<O> | undefined;

type RequiredOptionType<O extends Options | PositionalOptions> =
Expand Down
12 changes: 12 additions & 0 deletions types/yargs/yargs-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,18 @@ function Argv$inferRequiredOptionTypes() {

// $ExpectType (string | number)[]
yargs.option("x", { array: true, demandOption: true }).argv.x;

// $ExpectType string
yargs.option("x", { default: "default" as string | undefined, demandOption: true }).argv.x;

// $ExpectType string
yargs.option("x", { default: "default" as string | undefined, demand: true }).argv.x;

// $ExpectType string
yargs.option("x", { default: "default" as string | undefined, require: true }).argv.x;

// $ExpectType string
yargs.option("x", { default: "default" as string | undefined, required: true }).argv.x;
}

function Argv$inferMultipleOptionTypes() {
Expand Down

0 comments on commit 293f8fa

Please sign in to comment.