How to use TypeScript with Node.js
· Category: TypeScript
Short answer
Install TypeScript and Node type definitions, create tsconfig.json with Node settings, and run code with ts-node or compile to JS. For file system operations, see python read write files. For asynchronous programming, see python asyncio.
Steps
- Install:
npm install -D typescript @types/node ts-node - Create
tsconfig.jsonwith"module": "commonjs"and"target": "es2020" - Set
"outDir": "./dist"and"rootDir": "./src" - Run directly:
npx ts-node src/index.ts - Build and run:
npx tsc && node dist/index.js
Tips
- Use
tsxfor faster TypeScript execution in development - Configure path aliases in
tsconfig.jsonfor cleaner imports - For handling errors gracefully, see python error handling try except