TypeScript
Beginner
1 min read
Module Augmentation and Ambient Declarations
Example
// express-extension.d.ts — augment Express Request
import "express";
declare module "express-serve-static-core" {
interface Request {
user?: { id: number; email: string; role: string };
requestId: string;
}
}
// Now inside a middleware or route handler:
// req.user?.email — TypeScript knows about user
// global.d.ts — augment global Window
declare global {
interface Window {
__APP_VERSION__: string;
__FEATURE_FLAGS__: Record<string, boolean>;
}
// Augment process.env for Node.js
namespace NodeJS {
interface ProcessEnv {
NODE_ENV: "development" | "production" | "test";
DATABASE_URL: string;
JWT_SECRET: string;
PORT?: string;
}
}
}
export {}; // ensures file is treated as a module
// ambient.d.ts — describe a JS library without types
declare module "legacy-utils" {
export function formatCurrency(
amount: number,
currency: string,
locale?: string
): string;
export function slugify(text: string): string;
export const VERSION: string;
}
// Using the ambient declaration
import { formatCurrency, slugify } from "legacy-utils";
const price = formatCurrency(19.99, "USD", "en-US");
const slug = slugify("Hello World"); // "hello-world"
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript