Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 54 of 56 · Typescript

CLI Tool Project – `commander` in TypeScript

Duration: 25 minutes

Install commander

npm i commander
npm i -D @types/commander

Basic CLI

#!/usr/bin/env node
import { Command } from 'commander';

const program = new Command();

program
  .name('calc')
  .description('Simple arithmetic calculator')
  .option('-v, --verbose', 'Enable verbose output')
  .argument('<a>', 'first operand', parseFloat)
  .argument('<b>', 'second operand', parseFloat)
  .argument('<op>', 'operation: add|sub|mul|div')
  .action((a: number, b: number, op: string, opts) => {
    let result: number;
    switch (op) {
      case 'add': result = a + b; break;
      case 'sub': result = a - b; break;
      case 'mul': result = a * b; break;
      case 'div':
        if (b === 0) { console.error('Division by zero'); process.exit(1); }
        result = a / b; break;
      default:
        console.error('Unknown operation'); process.exit(1);
    }
    if (opts.verbose) console.info(`Calculating ${a} ${op} ${b}`);
    console.log(result);
  });

program.parse();

Make the file executable (chmod +x cli.ts) and add a bin entry in package.json:

"bin": { "calc": "dist/cli.js" }

Build with tsc and publish.

Info

Validate numeric arguments with a custom parseInt function to provide clearer error messages.

Previous: WebSockets Typed with `ws`Next: Project – Todo REST API (Express + TypeORM)