Object Arguments (Simple)
This is a simple example that demonstrates passing object-valued options to a command. Note that the object-valued options are passed as dot-notation strings. These can be nested for complex option structures that contain object properties that are themselves objects.
For a more detailed example showcasing defaults, required properties, validation, and JSON input, see the
object-argumentsmulti-file example.
Note: This example is a bit more abstract than the others, as real world use cases for object-valued options and especially nested objects are less common. This example is included to demonstrate the flexibility of the CLI Forge APIs and the ability to handle complex option structures with type safety.
1 FILESTry in Playground
All Example Files
FILE EXPLORER
object-dot-notation-simple.ts
1import cliForge from 'cli-forge';
2
3const cli = cliForge('object-notation', {
4 builder: (args) =>
5 args.option('foo', {
6 type: 'object',
7 properties: {
8 bar: {
9 type: 'object',
10 properties: {
11 baz: {
12 type: 'number',
13 },
14 },
15 },
16 qux: {
17 type: 'number',
18 },
19 arr: {
20 type: 'array',
21 items: 'number',
22 },
23 blam: {
24 type: 'string',
25 },
26 },
27 }),
28 handler: (args) => {
29 // Types should be inferred correctly
30 args.foo?.bar?.baz?.toFixed();
31 args.foo?.blam?.charAt(0);
32
33 // It's an array of numbers
34 args.foo?.arr?.reduce((acc, val) => acc + val, 0);
35 },
36});
37
38// We export the CLI for a few reasons:
39// - Testing
40// - Composition (a CLI can be a subcommand of another CLI)
41// - Docs generation
42export default cli;
43
44// Calling `.forge()` executes the CLI. It's single parameter is the CLI args
45// and they default to `process.argv.slice(2)`.
46if (require.main === module) {
47 (async () => {
48 await cli.forge();
49 })();
50}
51