How to define / get types of argv in command handler with yargs?

655 Views Asked by At

I am trying to create a CLI utility with Yargs but the types of argv in my command handlers are unknown. I installed @types/yargs as well but still cannot resolve the types. Any help would be greatly appreciated. I tried extending Yarg's ArgumentsCamelCase, but it does not allow me to use the type in the function declaration.

#!/usr/bin/env node

import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';

yargs(hideBin(process.argv));

(async () => {
  await yargs
    .scriptName('')
    .alias('v', 'version')
    .alias('h', 'help')
    .option('global', {
      alias: 'g',
      describe: 'perform globally',
      type: 'boolean',
    })
    .command({
      command: 'register [options]',
      describe: 'register',
      builder: {
        global: {
          alias: 'g',
          type: 'boolean',
          description: 'register globally',
          default: false,
        },
      },
      handler: async (argv) => {
          const { global } = argv //global is unknown type;
          // ...
      },
    })
    .command(
      'delete <id> [options]',
      'delete command with id',
      (yargs) => {
        yargs.option('id', {
          describe: 'The id',
          type: 'string',
        });
        yargs.option('global', {
          alias: 'g',
          type: 'boolean',
          description: 'delete globally',
          default: false,
        });
      },
      (argv) => {
        const {id, global} = argv; //both unknown
        // ...
      }
    )
    .strict()
    .parseSync();
})();
1

There are 1 best solutions below

0
sgedye On

This doesn't really answer your question, but hopefully will help someone else. If you are using typescript you can do the following:

import yargs from "yargs";

interface ExtendedArguments extends yargs.Arguments {
  sender?: string;
  recipient?: string;
}

const argv = yargs.argv as ExtendedArguments;
const SENDER_EMAIL = argv.email || "[email protected]";