2

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();
})();
ChrisGM
  • 33
  • 4
  • It seems that calling `command` discards the built type information of the options. Might want to open an issue about this. – kelsny Sep 16 '22 at 16:37
  • generated argument types with yargs aren't too reliable in my experience. I usually extract the builder function, and use the type `ReturnType['parseSync']>;` to type the arguments in the handler. Not ideal, since it's not entirely 1-1 sync, but it's an option – karizma Sep 16 '22 at 19:55

0 Answers0