Understand ambient module declarations, .d.ts files, DefinitelyTyped (@types), and global type augmentation.
Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
Many third-party npm packages are written in raw JavaScript without TypeScript source code. Declaration Files (.d.ts) provide type annotations for JavaScript code without altering the underlying JavaScript execution.
.d.ts File?A .d.ts file contains ONLY type declarations (no executable code). The TypeScript compiler uses it to provide autocompletion and type checking for untyped JavaScript libraries.
declare module)If an npm package lacks types, you can declare ambient module shapes in a local types.d.ts file:
// types/legacy-lib.d.ts
declare module "legacy-chart-library" {
export function renderChart(elementId: string, data: number[]): void;
export const version: string;
}
Now you can import and use the untyped library safely in your project:
import { renderChart } from "legacy-chart-library";
renderChart("my-canvas", [10, 20, 30]); // Fully typed!
Augment ambient global objects (like adding custom properties to window or Express Request):
declare global {
interface Window {
analyticsToken: string;
}
}
// Now valid throughout your project!
window.analyticsToken = "token_123";
declare statements. Including executable JavaScript code throws compile errors!Use DefinitelyTyped (npm i -D @types/node) for open-source library types. Next, let's explore the satisfies operator!