Modern examples of TypeScript integration with Node.js examples
Quick-start example of TypeScript integration with Node.js
Let’s start with the most common scenario: you have a Node.js project and you want to add TypeScript without blowing it up. This is the baseline that other examples of TypeScript integration with Node.js examples will build on.
mkdir ts-node-starter
cd ts-node-starter
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init
A minimal tsconfig.json that works well for Node.js in 2024 looks like this:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"]
},
"include": ["src"]
}
Create a simple entry file:
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Node + TypeScript"));
Wire it up in package.json using ts-node for dev and tsc for production builds:
{
"scripts": {
"dev": "ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
This tiny setup is the foundation that other examples include: Express APIs, workers, CLIs, and monorepos all rely on the same core pattern.
API-focused examples of TypeScript integration with Node.js examples
Most developers first meet TypeScript in Node.js through an HTTP API. Here’s a practical Express example of TypeScript integration with Node.js examples that you can adapt for any REST service.
Install Express with its types:
npm install express
npm install --save-dev @types/express
Create a typed Express server:
// src/server.ts
import express, { Request, Response } from "express";
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
interface Todo {
id: number;
title: string;
completed: boolean;
}
const todos: Todo[] = [];
app.get("/todos", (req: Request, res: Response<Todo[]>) => {
res.json(todos);
});
app.post("/todos", (req: Request<unknown, unknown, Todo>, res: Response<Todo>) => {
const todo: Todo = {
id: Date.now(),
title: req.body.title,
completed: false,
};
todos.push(todo);
res.status(201).json(todo);
});
app.listen(port, () => {
console.log(`API running at http://localhost:${port}`);
});
Update your scripts:
{
"scripts": {
"dev": "ts-node src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
}
}
This is one of the best examples of TypeScript integration with Node.js for teams migrating an existing Express app: you can gradually type your request bodies, responses, and route handlers without rewriting everything.
For a deeper look at API design and reliability (even though it’s not TypeScript-specific), resources like Harvard’s CS50 materials can help you level up your general backend thinking.
Real examples: TypeScript with Node.js and environment variables
Real-world apps live and die by configuration. Mis-typed environment variables are a classic production bug. Here’s an example of using TypeScript to make that safer in a Node.js project.
Install dotenv:
npm install dotenv
npm install --save-dev @types/dotenv
Create a typed config module:
// src/config.ts
import dotenv from "dotenv";
dotenv.config();
interface AppConfig {
NODE_ENV: "development" | "test" | "production";
PORT: number;
DATABASE_URL: string;
}
function requireEnv(key: string): string {
const value = process.env[key];
if (!value) {
throw new Error(`Missing environment variable: ${key}`);
}
return value;
}
export const config: AppConfig = {
NODE_ENV: (process.env.NODE_ENV as AppConfig["NODE_ENV"]) || "development",
PORT: Number(requireEnv("PORT")),
DATABASE_URL: requireEnv("DATABASE_URL"),
};
Use it in your server:
// src/server.ts
import express from "express";
import { config } from "./config";
const app = express();
app.get("/health", (_req, res) => {
res.json({ status: "ok", env: config.NODE_ENV });
});
app.listen(config.PORT, () => {
console.log(`Server listening on port ${config.PORT}`);
});
Among the real examples of TypeScript integration with Node.js examples, this one pays off quickly in production: missing variables fail fast at startup instead of causing weird runtime behavior.
Background worker example of TypeScript integration with Node.js
Not everything is an HTTP request. Many 2024-era backends rely heavily on background workers: queue consumers, schedulers, and cron jobs. Here’s how a worker can be typed cleanly.
Install a queue library, for instance bullmq (Redis-based):
npm install bullmq ioredis
Define typed job data and a worker:
// src/jobs/emailJob.ts
export interface EmailJobData {
to: string;
subject: string;
body: string;
}
// src/workers/emailWorker.ts
import { Worker, Job } from "bullmq";
import { EmailJobData } from "../jobs/emailJob";
const connection = { host: "127.0.0.1", port: 6379 };
const emailWorker = new Worker<EmailJobData>(
"email-queue",
async (job: Job<EmailJobData>) => {
const { to, subject, body } = job.data;
// Pretend sendEmail is implemented elsewhere
console.log(`Sending email to \({to}: }\(subject}`);
// await sendEmail(to, subject, body);
},
{ connection }
);
emailWorker.on("completed", (job) => {
console.log(`Email job ${job.id} completed`);
});
Producer script:
// src/producers/emailProducer.ts
import { Queue } from "bullmq";
import { EmailJobData } from "../jobs/emailJob";
const connection = { host: "127.0.0.1", port: 6379 };
const emailQueue = new Queue<EmailJobData>("email-queue", { connection });
async function queueWelcomeEmail(to: string) {
await emailQueue.add("welcome-email", {
to,
subject: "Welcome!",
body: "Thanks for signing up.",
});
}
queueWelcomeEmail("user@example.com").catch(console.error);
This is one of the best examples of TypeScript integration with Node.js for background processing: job payloads are typed from producer to consumer, catching mistakes at compile time.
Monorepo-style examples of TypeScript integration with Node.js examples
Larger teams often run Node.js in a monorepo with shared libraries. Yarn or pnpm workspaces plus TypeScript project references are the current go-to pattern.
Minimal workspace layout:
my-monorepo/
package.json
tsconfig.json
packages/
api/
package.json
tsconfig.json
src/
index.ts
shared/
package.json
tsconfig.json
src/
types.ts
Root package.json:
{
"private": true,
"workspaces": ["packages/*"]
}
Root tsconfig.json with project references:
{
"files": [],
"references": [
{ "path": "./packages/shared" },
{ "path": "./packages/api" }
]
}
Shared types:
// packages/shared/src/types.ts
export interface User {
id: string;
email: string;
}
API using shared types:
// packages/api/src/index.ts
import express, { Request, Response } from "express";
import { User } from "@my-org/shared"; // via workspace alias or paths
const app = express();
const users: User[] = [];
app.get("/users", (_req: Request, res: Response<User[]>) => {
res.json(users);
});
app.listen(3000, () => console.log("API running on 3000"));
This monorepo setup is a powerful example of TypeScript integration with Node.js examples in 2024: types and logic are shared across services, but the build remains manageable using project references.
For more on software engineering at scale, universities like MIT and Harvard publish open materials (for example, MIT OpenCourseWare) that pair well with this style of architecture.
Testing examples include Jest and ts-node for Node.js
Testing is where TypeScript either helps you or gets in your way. Done right, it speeds up refactors instead of slowing you down. Here’s how to integrate Jest with TypeScript in a Node.js codebase.
Install Jest and friends:
npm install --save-dev jest ts-jest @types/jest
npx ts-jest config:init
Update jest.config.cjs:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/tests/**/*.test.ts']
};
Example function and test:
// src/math/add.ts
export function add(a: number, b: number): number {
return a + b;
}
// tests/math/add.test.ts
import { add } from "../../src/math/add";
describe("add", () => {
it("adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});
});
Script:
{
"scripts": {
"test": "jest"
}
}
Among the many examples of TypeScript integration with Node.js examples, testing stands out as low effort, high payoff: once Jest is wired up, type-aware refactors become far less risky.
CLI tool example of TypeScript integration with Node.js
Node.js is still a popular way to build command line tools. TypeScript makes those CLIs less brittle, especially when parsing arguments.
Install a CLI helper, such as yargs:
npm install yargs
npm install --save-dev @types/yargs
Create a typed CLI script:
// src/cli.ts
#!/usr/bin/env node
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
interface Args {
name: string;
times: number;
}
const argv = yargs(hideBin(process.argv))
.option("name", {
type: "string",
demandOption: true,
describe: "Name to greet",
})
.option("times", {
type: "number",
default: 1,
describe: "How many times to greet",
})
.parseSync() as Args;
for (let i = 0; i < argv.times; i++) {
console.log(`Hello, \({argv.name}! (}\(i + 1})`);
}
Build and expose it via bin in package.json and you have a fully typed CLI tool. This is a straightforward example of TypeScript integration with Node.js that pays off when you later add subcommands and complex flags.
Modern ecosystem trends (2024–2025)
A few patterns stand out when you look at recent examples of TypeScript integration with Node.js examples in open-source projects and large companies:
- More projects are using
ts-nodeortsxonly for development, and compiling to plain JavaScript for production. - Node.js 20+ with native ESM is now common, pushing many TypeScript configs toward
module: "NodeNext". - Linting and formatting stacks are converging on ESLint + TypeScript ESLint + Prettier.
- Typed configuration (for environment variables, feature flags, and API schemas) is spreading fast.
For general trends in software adoption and workforce skills, the U.S. Bureau of Labor Statistics at bls.gov offers data that can help engineering leaders justify investment in stronger tooling like TypeScript.
FAQ: real examples of TypeScript integration with Node.js
Q1. What is a simple example of TypeScript integration with Node.js for beginners?
A very simple example is a single src/index.ts file with a typed function, a tsconfig.json targeting Node.js, and npm scripts using ts-node for dev and tsc plus node dist/index.js for start. From there you can grow into Express, workers, or CLIs.
Q2. How do I migrate an existing Node.js Express app to TypeScript?
Start by adding typescript, ts-node, and @types/node, plus @types/express. Rename one route file from .js to .ts, fix the obvious type errors, and run it through ts-node. Gradually convert files and tighten strict settings over time. The Express API section above shows one of the best examples of TypeScript integration with Node.js for this use case.
Q3. Are there examples of Node.js monorepos using TypeScript in production?
Yes. Many large organizations use Yarn or pnpm workspaces with TypeScript project references to share types and utilities across services. The monorepo section in this guide mirrors patterns used in real examples from open-source projects on GitHub and private company stacks.
Q4. Do I have to use ts-node, or can I just compile and run JavaScript?
You don’t have to use ts-node. A lot of teams in 2024–2025 use ts-node or tsx only for local development and testing, then compile with tsc in CI and run the generated JavaScript in production. That approach keeps startup fast and avoids shipping the TypeScript compiler to servers.
Q5. Where can I learn more about TypeScript and Node.js best practices?
The official TypeScript documentation is still the most reliable reference. For broader software engineering context, open courses from universities like MIT OpenCourseWare and Harvard’s CS50 are solid companions while you explore more advanced examples of TypeScript integration with Node.js examples.
Related Topics
Modern examples of diverse examples of TypeScript decorators
Modern examples of diverse examples of TypeScript generics
Modern examples of TypeScript integration with Node.js examples
Practical examples of TypeScript configuration examples for modern projects
Modern examples of TypeScript integration with React examples
Explore More TypeScript Code Snippets
Discover more examples and insights in this category.
View All TypeScript Code Snippets