Option Choices
This is a simple example that demonstrates how to limit choices for a given option.
Choices are checked after coerce if it is also provided, so be sure that the coerce function returns a value that is in the choices array.
Choices can be provided as an array of valid values or as a function that returns an array of valid values. Note that when returning the array from a function, providing "as const" is necessary to narrow the typing of the argument. This may not be possible if the choices are dynamic or need to be calculated at runtime, in which case the typing will remain as a broader type (e.g. string instead of 'a' | 'b').
1 FILESTry in Playground
All Example Files
FILE EXPLORER
choices.ts
1import cliForge from 'cli-forge';
2
3const cli = cliForge('basic-cli')
4 .demandCommand()
5 .command('hello', {
6 builder: (args) =>
7 args
8 .option('name', {
9 type: 'string',
10 description: 'The name to say hello to',
11 required: true,
12
13 // Choices limits valid values for the option.
14 // If the provided value is not in the choices array, an error will be thrown.
15 choices: ['sir', 'madame'],
16 })
17 .option('phrase', {
18 type: 'string',
19 default: 'hello',
20
21 // Choices can also be provided as a function that returns an array of valid values.
22 // This can be useful if the choices are dynamic or need to be calculated at runtime.
23 choices: () => ['hello', 'hi', 'hey'],
24 }),
25 // Handler is used to define the command's behavior
26 handler: (args) => {
27 // Note: args.name is typed as 'sir' | 'madame' due to the choices array
28 console.log(`${args.phrase}, ${args.name}!`);
29 },
30 });
31
32export default cli;
33
34if (require.main === module) {
35 (async () => {
36 await cli.forge();
37 })();
38}
39