Sub topic 1
Building a Small Command-Line App in TypeScript
Prerequisites
Assume basic JavaScript or TypeScript, async/await, Node.js, npm, and simple terminal commands. This chapter uses Node.js ESM, which is Node's modern module system.
Setting up the project
Create a project and install TypeScript plus Node.js type definitions:
mkdir wcl && cd wcl
npm init -y
npm install --save-dev typescript @types/node
mkdir srcThe src directory holds TypeScript. The compiler will place JavaScript in dist.
Configuring the TypeScript compiler for Node.js
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"]
},
"include": ["src"]
}target selects the JavaScript version. module and moduleResolution make TypeScript follow Node's ESM rules. strict enables stronger checks. rootDir and outDir define the source and build directories.
Mark the package as ESM in package.json:
{
"name": "wcl",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "tsc"
}
}Writing the entry point
Create src/cli.ts. The shebang lets Unix-like systems execute the compiled file as a command.
#!/usr/bin/env node
import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" }
},
allowPositionals: true
});
if (values.help || positionals.length === 0) {
console.log("usage: wcl [-l] <file>");
} else {
console.log({
file: positionals[0],
linesOnly: values.lines ?? false
});
}Parsing flags and positional arguments
A flag is an option such as --lines or -l. A positional argument is a value supplied without an option name, such as notes.txt. parseArgs separates these values and checks the declared option types.
Exercise
Which compiler option makes TypeScript report more potential mistakes?
Show answer
"strict": true enables strict type checking.