Skip to content

Instantly share code, notes, and snippets.

@dsmrt
Last active December 9, 2024 18:23
Yargs Typescript CommandModule Generics
import { CommandModule, Argv, Options, ArgumentsCamelCase } from 'yargs'
export interface MyOptions extends Options {
interactive: boolean
env: string
color: string
}
export class MyCommand<U extends MyOptions> implements CommandModule<{}, U> {
public command = 'my-cmd'
public describe = 'Just a simple generics example'
public builder = (args: Argv): Argv<U> => {
args.option('interactive', { boolean: true, alias: 'i', describe: 'get interactive with it!' })
args.option('env', { string: true, alias: 'e', describe: 'Environment' })
args.option('color', { boolean: true, describe: 'disable color', default: true })
return args as unknown as Argv<U>
}
public handler = async (args: ArgumentsCamelCase<U>) => {
// type hinting works with the following!
console.log(
args.color,
args.env,
args.interactive
)
}
}
@i-yusuf
Copy link

i-yusuf commented Aug 24, 2024

import { CommandModule, Arguments, Argv } from 'yargs';

interface CommandArgs {
  arg?: string;
}

export class ConfigureCommand implements CommandModule {
  public command = '';
  public describe = '';

  public builder(args: Argv): Argv<CommandArgs> {
    return args.positional('arg', {
      describe: 'Hello world!',
      type: 'string',
    });
  }

  public handler(argv: Arguments<CommandArgs>) {
    console.log(argv);
  }
}

or

import { CommandModule, Arguments, Argv } from 'yargs';

interface CommandArgs {
  arg?: string;
}

export class ConfigureCommand implements CommandModule<{}, CommandArgs> {
  public command = '';

  public describe = '';

  public builder(args: Argv<{}>) {
    return args.positional('arg', {
      describe: 'Hello world!',
      type: 'string',
    });
  }

  public handler(argv: Arguments<CommandArgs>) {
    console.log(argv);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment