Arguments Of
When building a CLI, and especially if taking advantage of composition, it can be necessary to have a typescript type that respresents the resolved arguments of a CLI command. For example, if you abstract the handler of a command into a separate function, the argument of that function would be typed as the arguments of the CLI command.
CLI Forge provides the ArgumentsOf type to help with this. It takes a CLI instance or a function that returns a CLI instance and returns the type of the arguments that the CLI command handler will receive. There are some difficulties with typescript support for circular references, so its usage isn't perfect, but if used with composable builders directly you avoid these problems.
1 FILESTry in Playground
All Example Files
FILE EXPLORER
arguments-of.ts
1import { ArgumentsOf, chain, cli, CLI, makeComposableBuilder } from 'cli-forge';
2
3const withName = makeComposableBuilder((args) =>
4 args.option('name', {
5 type: 'string',
6 description: 'Your name',
7 required: true,
8 })
9);
10
11const withAge = makeComposableBuilder((args) =>
12 args.option('age', {
13 type: 'number',
14 description: 'Your age',
15 required: true,
16 })
17);
18
19const builder = <T extends CLI>(args: T) => chain(args, withName, withAge);
20
21const myCLI = cli('arguments-of', {
22 builder: (args) => builder(args),
23 handler: (args) => CLIHandler(args),
24});
25
26type Arguments = ArgumentsOf<typeof builder>;
27
28function CLIHandler(args: Arguments) {
29 console.log(`Hello, ${args.name}!`);
30 console.log(`You are ${args.age.toFixed(0)} years old.`);
31}
32
33if (require.main === module) {
34 (async () => {
35 await myCLI.forge();
36 })();
37}
38