TypeScript by Example

Hello, World

Running TypeScript with tsx and compiling with tsc - the two modes every TypeScript project uses.

TypeScript is JavaScript with a type layer on top. Every TypeScript file compiles to JavaScript before it runs - understanding the two execution modes (run directly with tsx, compile with tsc) is the first thing to nail down.

tsx runs TypeScript directly without a separate compile step. It uses esbuild under the hood, strips types at runtime, and is the fastest way to run a .ts file in development.

// hello.ts
const message: string = "Hello, World!";
console.log(message);
OUTPUT
$ npx tsx hello.ts
Hello, World!

tsc compiles TypeScript to JavaScript and performs full type checking. The output is plain .js that any Node.js version compatible with your configured target and module can run.

A minimal tsconfig.json tells tsc which files to compile and what JavaScript version to target.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "outDir": "dist"
  }
}
OUTPUT
$ npx tsc
$ node dist/hello.js
Hello, World!

In production

ts-node has significant startup cost because it uses the TypeScript compiler for every run. Prefer tsx (esbuild-backed) in development and scripts - it starts in milliseconds. For production Node.js services, always precompile with tsc and ship the .js output. Never ship .ts files to production: runtime transpilation adds startup latency, and tools like AWS Lambda and Google Cloud Run optimize for cold-start times where every millisecond counts.

Enjoyed this? Get more software craft delivered to your inbox.