When a JavaScript library has no types, an internal module is still evolving, or a package exposes an API that its declarations describe poorly, a well-designed .d.ts file can restore useful editor support without rewriting the implementation. This guide explains how to write TypeScript declaration files for modules, globals, functions, classes, overloads, and generics—and provides a checklist for testing and maintaining them as the JavaScript API changes.
Overview
A TypeScript declaration file describes an API without providing its runtime implementation. It contains type information such as function signatures, class members, exported values, interfaces, and namespaces. The declaration compiler option can generate these files from TypeScript source, but hand-written declarations are useful when the implementation remains JavaScript or when an existing declaration is incomplete.
The first question is whether the JavaScript code is a module or a script. A module uses import or export syntax, or is treated as a module by the project configuration. A script places declarations in the global scope. This distinction affects whether you write declare module, use top-level exports, or add declarations to the global namespace.
A declaration file should describe observable behavior, not implementation details. If a JavaScript function accepts a string and returns an object with a stable shape, declare that contract. If the runtime accepts several forms, represent those forms explicitly rather than choosing the narrowest convenient type. The goal is accurate type-safe JavaScript development, not simply making compiler errors disappear.
Starter declaration template
declare module "legacy-format" {
export interface FormatOptions {
indent?: number;
sortKeys?: boolean;
}
export function format(value: unknown, options?: FormatOptions): string;
export class Formatter {
constructor(options?: FormatOptions);
format(value: unknown): string;
}
export default format;
}
This template assumes that consumers import the package as legacy-format and that the runtime exposes the named and default exports shown. Do not copy the export style automatically: verify the JavaScript entry point, package exports, and actual import patterns first.
Checklist by scenario
1. An untyped package or external JavaScript module
- Identify the exact module specifier used by consumers, such as
legacy-formatorlegacy-format/parser. - Place the declaration where the compiler can find it through the project’s included files, configured type roots, or package metadata.
- Wrap an ambient package declaration in
declare module "module-name". - Describe every supported export: default values, named functions, classes, constants, and types.
- Verify the declaration with a real import in a test fixture.
For a local module that is part of your source tree, a file such as parser.d.ts can usually use ordinary module syntax instead:
export interface ParseResult {
value: unknown;
warnings: string[];
}
export function parse(input: string): ParseResult;
Using top-level export makes the file an external module. An ambient declare module is more appropriate when you are describing a module by name from outside its implementation.
2. Functions with overloads
Use overloads when the return type depends on the input shape and the runtime genuinely supports distinct call forms.
export function read(path: string): string;
export function read(path: string, encoding: "json"): Record<string, unknown>;
export function read(path: string, encoding?: "text" | "json"): string | Record<string, unknown>;
Put specific overloads before broad ones. The implementation signature is not available to consumers in a declaration file, so the overload list must communicate the complete public API. If a function’s result does not depend on its arguments, a single union or object type may be clearer than several overloads.
3. Generic functions and classes
Use a type parameter when the API preserves a relationship between input and output. Avoid adding generics merely to make a declaration appear advanced.
export function first<T>(items: readonly T[]): T | undefined;
export interface Client<TResponse> {
request(path: string): Promise<TResponse>;
}
export class Cache<T> {
get(key: string): T | undefined;
set(key: string, value: T): void;
}
If the JavaScript API accepts only objects with a particular property, constrain the parameter: function getId<T extends { id: string }>(value: T): string. Use unknown for values whose runtime type is not known; reserve any for a deliberate escape hatch that you document and test.
4. A library that combines a callable function and properties
Some JavaScript libraries export a function that also has methods or constants attached to it. A function declaration and namespace declaration can merge to describe this shape.
export = toolkit;
declare function toolkit(input: string): string;
declare namespace toolkit {
const version: string;
function normalize(input: string): string;
}
This pattern represents CommonJS-style APIs that behave like both a callable value and a namespace. Match it to the runtime and package configuration; do not replace it with a default export unless consumers actually use default-import syntax supported by the project.
5. A global script or browser-provided value
For a script that creates a global, declare the value at the top level of a script-style declaration file:
declare const analytics: {
track(eventName: string, properties?: Record<string, unknown>): void;
};
If the global is an addition to an existing module or interface, use declaration merging carefully:
declare global {
interface Window {
analytics: {
track(eventName: string): void;
};
}
}
export {};
The empty export makes the file a module while declare global places the augmentation in the global scope. Confirm that the runtime really installs the property; declaration merging changes the type system, not the JavaScript object.
Quick syntax reference
| Need | Typical syntax | Check |
|---|---|---|
| Named function | export function parse(input: string): Result; | Arguments and return value match runtime behavior. |
| Default export | export default createClient; | Consumers really use the default export. |
| Ambient package | declare module "package-name" { ... } | The module specifier is exact. |
| Generic API | function map<T, U>(...): U[] | The type relationship is preserved. |
| Global value | declare const library: Library; | The script loads before the value is used. |
| CommonJS callable export | export = library; | Module settings and import style support it. |
What to double-check
Test declarations as consumers use them. Create small fixture files that import the module, call each supported overload, instantiate each public class, and assert expected types with compiler errors where appropriate. A declaration test should fail if a valid usage stops compiling or an invalid usage becomes accepted.
Check module resolution as well as syntax. A declaration can be perfectly valid but invisible because its directory is excluded, its package metadata points elsewhere, or the import path differs from the declared module name. Test with the same tsconfig.json and module-resolution settings used by the application.
Compare the declaration against runtime evidence: JavaScript source, documentation, integration tests, and actual exports. For changing internal modules, keep a fixture beside the implementation or package-level tests that exercise the public boundary. The testing patterns in Testing TypeScript Applications can help separate runtime tests from type-level checks.
When publishing a package, verify the relationship among types, exports, ESM, and CommonJS entry points. A declaration file that describes one entry point does not automatically describe every subpath. The package release checklist in How to Publish a TypeScript Package is useful for this boundary.
Common mistakes
- Declaring the implementation twice: A
.d.tsfile should describe an existing runtime module. It does not create functions or classes. - Using
anyeverywhere: This removes useful feedback. Prefer precise types, unions, generics, orunknownat untrusted boundaries. - Guessing optionality: An omitted property, an explicit
undefined, and a required property are not always interchangeable. Match how the JavaScript code reads and validates values. - Ignoring export shape:
export default, named exports,export =, and global values lead to different consumer syntax. - Overloading too broadly: A broad first overload can prevent later, more specific overloads from being selected.
- Forgetting side effects: A module may install a global or augment a prototype when imported. Document the type effect separately from the runtime side effect.
- Relying on declarations for validation: Types disappear at runtime. Parse external data and validate it at the boundary when the input is untrusted.
When to revisit
Revisit a declaration file whenever the JavaScript API changes, a new export is added, an import path moves, or consumers report that editor completion does not match runtime behavior. Also review declarations when upgrading TypeScript, changing module-resolution settings, switching between ESM and CommonJS, or reorganizing package exports. Compiler behavior and supported declaration syntax can evolve between major releases, so keep the fixture project on the versions used by the application or package.
Use this final checklist before merging:
- List the runtime’s actual public exports and compare them with the declaration.
- Confirm whether the API is a module, a global script, a callable export, or a combination.
- Model overloads and generics only where they express real input-output relationships.
- Replace unexplained
anywith a safer type or add a comment explaining the boundary. - Compile consumer fixtures using the project’s real configuration.
- Run runtime tests for behavior and type-level tests for the declaration contract.
- Update the declaration and its tests together when the JavaScript API changes.
For broader migration work, pair this process with the JavaScript to TypeScript migration guide. A small, tested declaration is often the safest first step toward typed consumers, and it can later be replaced or refined as the implementation moves into TypeScript.