Command Line Flags in TypeScript
Here’s the translation of the Go code to TypeScript, along with explanations in Markdown format suitable for Hugo:
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.
TypeScript doesn’t have built-in support for command-line flag parsing, so we’ll use a popular library called yargs to implement our example command-line program.
First, install the yargs package:
npm install yargsNow, let’s create our TypeScript program:
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const argv = yargs(hideBin(process.argv))
.option('word', {
type: 'string',
description: 'a string',
default: 'foo'
})
.option('numb', {
type: 'number',
description: 'a number',
default: 42
})
.option('fork', {
type: 'boolean',
description: 'a boolean',
default: false
})
.option('svar', {
type: 'string',
description: 'a string var',
default: 'bar'
})
.parse();
console.log('word:', argv.word);
console.log('numb:', argv.numb);
console.log('fork:', argv.fork);
console.log('svar:', argv.svar);
console.log('tail:', argv._);In this TypeScript version:
- We import
yargsandhideBinhelper function. - We use
yargsto define our command-line options, similar to the flag declarations in the original code. - The
parse()method is called to process the command-line arguments. - We access the parsed values directly from the
argvobject.
To run this TypeScript program, you’ll need to compile it first:
tsc command-line-flags.tsThen you can run the compiled JavaScript:
node command-line-flags.js -word=opt -numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: []If you omit flags, they automatically take their default values:
node command-line-flags.js -word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []You can provide trailing positional arguments after any flags:
node command-line-flags.js -word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: [ 'a1', 'a2', 'a3' ]To get automatically generated help text, use the --help flag:
node command-line-flags.js --help
Options:
--help Show help [boolean]
--version Show version number [boolean]
--word a string [string] [default: "foo"]
--numb a number [number] [default: 42]
--fork a boolean [boolean] [default: false]
--svar a string var [string] [default: "bar"]If you provide a flag that wasn’t specified, the program will print an error message:
node command-line-flags.js --wat
Unknown argument: watThis TypeScript version provides similar functionality to the original program, using the yargs library to handle command-line argument parsing.