Run TypeScript scripts with tsx
Run a TypeScript script with tsx, pass command-line arguments through pnpm, and check types with tsc.
You need a one-off script to print a report from a few records. The project uses TypeScript, but its build compiles the whole app. Run the script on its own with tsx and keep the app build out of that loop.
Run the source file
From a project that uses pnpm, add the runner with pnpm add -D tsx. Make a file named report.ts in the project root.
type Row = { product: string; count: number }
const rows: Row[] = [
{ product: 'Notebook', count: 4 },
{ product: 'Pencil', count: 7 },
]
const minimum = Number(process.argv[2] ?? '0')
if (!Number.isFinite(minimum)) {
throw new Error('Give a numeric minimum')
}
for (const row of rows) {
if (row.count >= minimum) {
console.log(`${row.product}: ${row.count}`)
}
}With pnpm exec tsx report.ts 5, you see Pencil: 7 and no output file to clean up.
The command finds the project’s copy of tsx. The runner transforms the TypeScript and runs the result in Node. The 5 belongs to your script and shows up at process.argv[2]. With no argument, the threshold is zero and the script prints both rows.
Put the command in package.json as a script when the utility becomes part of the project workflow. Name it report and set its value to tsx report.ts. Then pnpm run report 5 passes the same argument without making anyone remember the file name.
Keep the type check in the project
Running a script and checking it are separate steps. esbuild's TypeScript transform, which tsx uses, removes the type annotation on rows. It leaves the value alone. Change the pencil’s count to the string '7' and the report still runs here because the numeric comparison coerces the string.
Run pnpm exec tsc --noEmit with the script included in your TypeScript project. With the string count in place, the checker reports that string is not assignable to number. Make sure the project has Node types if it reports that it cannot find process. A frontend tsconfig may include just the app’s source directory, so check which config actually includes the utility.
The argument guard still matters after the type check. Run pnpm exec tsx report.ts nope and the guard throws Give a numeric minimum. Keep that check at the point where you turn a shell argument into a number.