Command Line Arguments in TypeScript

Command-line arguments are a common way to parameterize execution of programs. For example, node hello.js uses hello.js as an argument to the node program.

import * as process from 'process';

// process.argv provides access to raw command-line
// arguments. Note that the first two values in this array
// are the path to the Node.js executable and the path to the script,
// and process.argv.slice(2) holds the arguments to the program.
const argsWithProg = process.argv;
const argsWithoutProg = process.argv.slice(2);

// You can get individual args with normal indexing.
const arg = process.argv[4];

console.log(argsWithProg);
console.log(argsWithoutProg);
console.log(arg);

To experiment with command-line arguments it’s best to save this in a file (e.g., command-line-arguments.ts) and run it with ts-node:

$ ts-node command-line-arguments.ts a b c d
['/path/to/node', '/path/to/command-line-arguments.ts', 'a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
c

Next we’ll look at more advanced command-line processing with argument parsing libraries.