Write Ambient Module Declarations for NPM Packages
You'll learn how to provide TypeScript types for third-party JavaScript packages that don't have their own type definitions.
What This Solves
You've added a fantastic NPM package to your project, but when you import it, TypeScript complains: "Could not find a declaration file for module 'cool-library'." The library works perfectly at runtime (it's just JavaScript), but TypeScript has no idea what types it should use.
This is where declare module 'module-name' saves the day. It lets you write ambient declarations that describe the shape of an external package.
The Basic Pattern
When you write declare module 'package-name', you're creating a "type signature" for an entire NPM package. Think of it as writing a menu for a restaurant that doesn't have one—you're describing what's available without changing the actual food.
The syntax looks like this:
declare module 'some-untyped-package' {
export function doSomething(input: string): number;
export const version: string;
}
Now when you import { doSomething } from 'some-untyped-package', TypeScript knows exactly what types to expect.
Where to Put These Declarations
You typically create a .d.ts file (like types.d.ts or external-types.d.ts) in your project. TypeScript automatically picks up these ambient declarations without needing explicit imports.
Describing Real Package Shapes
For a package that exports a default function and some named exports:
declare module 'legacy-validator' {
export default function validate(data: unknown): boolean;
export function validateEmail(email: string): boolean;
export const maxLength: number;
}
For a package that exports a single class:
declare module 'old-logger' {
export default class Logger {
constructor(name: string);
log(message: string): void;
error(message: string): void;
}
}
When to Use This
This technique is your bridge when:
- A package has no TypeScript types and isn't on DefinitelyTyped
- You need quick types for internal/private packages
- You're gradually migrating a JavaScript codebase
- The official types are broken and you need a temporary fix
Key Takeaway: declare module 'package-name' lets you create ambient type definitions for any NPM package, giving you type safety even when the original library is plain JavaScript.