Skip to content

access options directly via key #1110

@goodmanpersonguy

Description

@goodmanpersonguy

I created a new Typescript project for a little CLI. I want to create multiple commands, so on startup I pass the program object to those commands via loop

app.ts

const commands: Command[] = [new AddCommand()];

async function bootstrap() {
	const program: Program = new Program();
	program.version(version);

	for (let i = 0; i < commands.length; i++) {
		commands[i].load(program);
	}

	program.parse(process.argv);
}
bootstrap();

Each command implements a helper interface

command.ts

export interface Command {
	load(program: Program): void;
}

Finally I have a command that should access an option by key. This option determines if the code should use the current working Directory

export class AddCommand implements Command {
	load(program: Program): void {
		program
			.command(`add [directory]`)
			.alias('a')
			.option('-c, --current', 'Use the current working directory')
			.action(async (directory: string, options: any) => {
				console.log(program.c); // undefined
				console.log(program.current); // undefined
				console.log(options.c); // undefined
				console.log(options.current); // undefined
				console.log(program.options.c); // undefined
				console.log(program.options.current); // undefined
				console.log(options.parent.args[0]); // ./src
				console.log(process.argv[3]); // ./src
			});
	}
}

As you can see I have to access the options via array index. How can I access the current option directly?

What I call in the terminal:

npm run dev a ./src -c

I created a minimal repository for reproduction

https://github.com/goodmanpersonguy/commander-cli

Thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions