Node.js and TypeScript

TypeScript adds types, editor support, and safer refactors to Node projects. Node does not execute TypeScript source directly in the usual runtime path; you compile it or run it through a TypeScript-aware loader.

How it runs

TypeScript is a compile-time type checker and language superset that erases type annotations to produce standard JavaScript. In production, compile TypeScript to dist/ ahead of time and run plain node dist/app.js; during local development, a fast loader or Node's built-in type stripping avoids a slow manual rebuild step:

  1. Write typed .ts source files under src/ with "strict": true in tsconfig.json.
  2. Run tsc --noEmit in CI to catch type errors across the whole project.
  3. Execute locally with tsx (or compile to dist/ with tsc for production containers).

Common tooling

Pick tooling that keeps local iteration fast while still running full type checks before deployment:

  • tsc: The official TypeScript compiler; authoritative for type checking and emitting dist/ JavaScript + declaration files.
  • tsx: Fast esbuild-backed runner for local development and scripts without configuring complex loaders.
  • @types/node: Type definitions for Node built-in modules (node:fs, node:http, process).

Keep compiled output (dist/) separate from authored source (src/) and git-ignored so generated files never drift from TypeScript source:

src/
  app.ts
  config/
  routes/
  services/
  types/
dist/
  app.js

Typing guidelines

TypeScript checks types at compile time and erases them at runtime—it cannot protect your server from malformed JSON sent over HTTP:

  • Explicit public contracts: Type exported function parameters, return types, and service interfaces explicitly.
  • Name domain models: Prefer named interface or type aliases over repeated inline object shapes.
  • Validate at boundaries: Always validate untrusted request bodies and environment variables at runtime (for example, with Zod or manual guards) before casting to a TypeScript type.

Practice

Set up a minimal typed Node script and verify compile-time checks:

  1. Initialize tsconfig.json with "strict": true and install @types/node.
  2. Write a typed parsePort(raw: string | undefined): number helper and run tsc --noEmit.
  3. Explain why req.body as User without runtime validation is unsafe in an HTTP handler.