A TypeScript utility for building type-safe CLI commands using commander and zod.
npm install zod-commanderA TypeScript utility for building type-safe CLI commands using commander and zod.
zod-commander lets you define type-safe CLI commands using zod schemas for arguments and options, with a simple API.
``ts
import { Command } from 'commander'
import { z } from 'zod'
import { zodCommand } from 'zod-commander'
// Define a command using zodCommand
const greet = zodCommand({
name: 'greet',
description: 'Say hello to someone',
args: {
name: z.string().describe('Name of the person to greet'),
},
opts: {
excited: z.boolean().default(false).describe('e;Add an exclamation mark'), // 'e;' makes -e an alias
},
async action({ name }, { excited }) {
console.log(Hello, ${name}${excited ? '!' : '.'})
},
})
// Create a CLI program and add the command
const program = new Command()
program
.name('my-cli')
.description('A demo CLI using zod-commander')
.version('1.0.0')
.addCommand(greet)
.parseAsync(process.argv)
`
- Type-safe arguments and options: Use zod schemas to define and validate CLI inputs.
- Booleans are treated as flags: Any boolean option automatically becomes a CLI flag (e.g. --excited)..describe()
- Descriptive help: on schemas provides help text for each argument/option..default()
- Default values: Use on zod schemas for default option values.action
- Async actions: The function can be async and receives parsed args and opts."f;The file to export to"
- No boilerplate: Just export your command; integrate with your CLI runner as needed.
- Aliases for options: If you start a description with a letter and a semicolon (e.g. ), that letter will be used as a short alias (e.g. -f).--help
- Perfect help output: The generated help text is clear and complete—try running your command with to see for yourself!
Currently, the package uses zod v3 by default. Zod version can be specified by importing the appropriate version from the zod3 or zod4 submodules.
`tsimport { zodCommand } from 'zod-commander'
import { zodCommand } from 'zod-commander/zod4'
// or
import { zodCommand } from 'zod-commander/zod3' // equivalent to `
In the future, the default version will be changed to zod v4.
> [!NOTE]
> To use zod-commander/zod4 in the same way as zod-commander/zod3, you should use .prefault() instead of .default()`.