How to use TypeScript with Node.js
· Category: TypeScript
Short answer
Write your Node.js application in .ts files, install @types/node for built-in module types, and run with ts-node, tsx, or a compiled outDir.
Steps
- Install TypeScript and Node types:
npm install -D typescript @types/node - Set
moduleandmoduleResolutionappropriately (CommonJSorNodeNext). - Set
targetto a supported ECMAScript version for your Node.js runtime. - Use
ts-nodefor development:ts-node src/index.ts. - Compile for production:
tscand runnode dist/index.js.
Tips
tsxis a faster modern alternative tots-nodethat uses esbuild.- Use
NODE_ENVtypes with declaration merging onProcessEnvfor autocomplete.
Common issues
- Missing
@types/nodecauses errors onrequire,process, andBuffer. - Mismatched
modulesettings between TypeScript and your runtime lead to import errors.