Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug] command option's choises is of type unknown #2397

Open
its-dibo opened this issue Apr 8, 2024 · 4 comments
Open

[bug] command option's choises is of type unknown #2397

its-dibo opened this issue Apr 8, 2024 · 4 comments

Comments

@its-dibo
Copy link

its-dibo commented Apr 8, 2024

let args  = yargs()
 .command('example', '...', {
   test:{
     choices: ["a", "b"] as const;
   }
})
.parseSync()

//<------- error: Argument of type 'unknown' is not assignable to parameter of type '"a" | "b"'.ts(2345)
test(args._[0].test)

function test(value: 'a' | 'b'){}
@shadowspawn
Copy link
Member

I was not able to reproduce this problem. I created a new package and initialised the TypeScript configuration with npx tsc --init.

import yargsFactory from 'yargs/yargs';

const argv  = yargsFactory(process.argv.slice(2))
 .command('example', '...', {
   test:{
     choices: ["a", "b"] as const
   }
})
.parseSync();

console.log(argv);
% node ts.js example --test  
ts.js example

...

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]
  --test                                                     [choices: "a", "b"]

Invalid values:
  Argument: test, Given: true, Choices: "a", "b"

@its-dibo
Copy link
Author

its-dibo commented Apr 9, 2024

% node ts.js example --test 

this is not the issue, yargs itself can detect the user's input.
but the issue is that there is no way to tell typescript the correct type, you need to always cast each arg before using it

To reproduce the issue:
1- starting from your snippet, add a single line argv.test
2- hover over argv.test to see its type. it should be something like a | b, but instead it is just unknown

@shadowspawn
Copy link
Member

(I misunderstood the issue. Thanks for explaining. I will have another look.)

@shadowspawn
Copy link
Member

Here is a way of defining the command that gets the choices into the types.

import yargsFactory from 'yargs/yargs';

const yargs = yargsFactory(process.argv.slice(2))
  .command('example [test]', '...',
    (yargs) => {
      return yargs.positional('test', {
        type: 'string',
        choices: ["a", "b"] as const
      });
    },
    (argv) => {
      console.log(argv);
      const inspect = argv.test; // <-- "a" | "b" | undefined
    });

yargs.parseSync();

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

No branches or pull requests

2 participants