Node.js and TypeScript
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:
- Write typed
.tssource files undersrc/with"strict": trueintsconfig.json. - Run
tsc --noEmitin CI to catch type errors across the whole project. - Execute locally with
tsx(or compile todist/withtscfor 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 emittingdist/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).
Recommended structure
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
interfaceortypealiases 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:
- Initialize
tsconfig.jsonwith"strict": trueand install@types/node. - Write a typed
parsePort(raw: string | undefined): numberhelper and runtsc --noEmit. - Explain why
req.body as Userwithout runtime validation is unsafe in an HTTP handler.