Introduction to Declaration Files
TypeScript declaration files are files with the .d.ts extension that describe the types and public interfaces of existing code. They tell the TypeScript compiler which functions, classes, variables, properties, and other declarations are available without providing their runtime implementations.
Declaration files are especially useful when working with JavaScript libraries, existing JavaScript applications, third-party npm packages, and code that needs to expose a type-safe API. A JavaScript module can provide the actual functionality, while its declaration file describes how TypeScript consumers should use that functionality.
For example, a library may export a function that calculates a total price. Its JavaScript implementation contains the calculation, while a declaration file tells TypeScript which arguments the function accepts and what type of value it returns. This enables editor suggestions and compile-time checking without rewriting the original JavaScript implementation.
1. What Is a .d.ts File?
A declaration file describes types without implementing the corresponding runtime behavior. TypeScript uses the declarations to understand the available API when analyzing code that imports or references it.
Consider an ordinary JavaScript utility module:
// math-utils.js
export function add(first, second) {
return first + second;
}
A corresponding declaration file can describe that function:
// math-utils.d.ts
export declare function add(
first: number,
second: number
): number;
The declaration tells TypeScript that add accepts two numbers and returns a number. The JavaScript file remains responsible for calculating the result at runtime.
A TypeScript consumer can import the function and benefit from the declared signature:
// app.ts
import { add } from "./math-utils";
const total = add(100, 50);
console.log(total);
// Compile-time error:
// add("100", 50);
Assuming TypeScript resolves the declaration file, it can report that the string argument is incompatible with the declared parameter type. The declaration itself does not perform runtime validation or change the JavaScript implementation.
2. Understanding the declare Keyword
The declare keyword tells TypeScript that a value, function, class, variable, or other supported declaration exists outside the current declaration statement and provides type information about it. It does not create a runtime implementation.
// global-utils.d.ts
declare function formatName(name: string): string;
declare const platformVersion: string;
These declarations tell TypeScript that a function named formatName and a value named platformVersion exist. They do not define the function body or initialize the variable.
If the real application does not provide those values, the code can still fail at runtime even though the declaration file makes the names recognizable to the compiler.
Declaration files commonly use declare for ambient descriptions of external APIs. By contrast, ordinary TypeScript source files can provide actual implementations and export them for other modules to import.
Use declarations only when the corresponding runtime functionality genuinely exists. Incorrectly declaring nonexistent variables or functions can hide compiler errors while leaving the application broken.
3. Declaring Functions and Variables
Declaration files can describe functions and variables that come from JavaScript modules, browser integrations, external scripts, or other runtime environments.
// utility-library.d.ts
export declare function formatCurrency(
amount: number,
currencyCode: string
): string;
export declare function calculateDiscount(
price: number,
discountPercent: number
): number;
export declare const libraryVersion: string;
Each declaration describes the public signature of a function or variable. TypeScript can use these signatures to validate how consumers access the library.
The parameter names are useful documentation, while the parameter and return types provide the information used for static checking. The implementation may exist in a JavaScript file, a compiled package, or another runtime-provided resource.
You can also describe optional parameters, union types, generic functions, and overloads in declaration files. The declarations should accurately describe the supported behavior rather than introducing types that the actual implementation does not honor.
4. Declaring Interfaces, Types, and Objects
Declaration files can export interfaces and type aliases that describe the objects and values a library exposes. This is particularly useful when JavaScript code provides objects with a stable, documented structure.
// course-library.d.ts
export interface Course {
id: number;
title: string;
published: boolean;
}
export type CourseStatus =
| "draft"
| "published"
| "archived";
export declare function getCourse(id: number): Course | undefined;
export declare function getCourseStatus(
course: Course
): CourseStatus;
A consumer can import both the runtime functions and the types:
// app.ts
import {
getCourse,
getCourseStatus
} from "./course-library";
import type {
Course,
CourseStatus
} from "./course-library";
const course: Course | undefined = getCourse(101);
if (course) {
const status: CourseStatus = getCourseStatus(course);
console.log(course.title);
console.log(status);
}
The Course interface describes the shape of a course object, while CourseStatus restricts status values to a known set of strings.
The return type Course | undefined communicates that a lookup might not find a record. TypeScript can then require consumers to handle the missing result before accessing course properties.
Interfaces and type aliases exist only in TypeScript's type system. They do not create JavaScript objects or validate actual data at runtime.
5. Declaration Files for Classes
A declaration file can describe a class that is implemented elsewhere. It specifies the class's constructor, public properties, and methods without providing their implementations.
// course.d.ts
export default class Course {
id: number;
title: string;
constructor(id: number, title: string);
getTitle(): string;
rename(title: string): void;
}
The declaration describes a default-exported class named Course. It tells consumers which members are available and what arguments the constructor and methods expect.
An implementation could exist in a JavaScript module:
// course.js
export default class Course {
constructor(id, title) {
this.id = id;
this.title = title;
}
getTitle() {
return this.title;
}
rename(title) {
this.title = title;
}
}
The implementation must match the declaration. If the declaration promises a method that does not exist in the actual JavaScript class, TypeScript consumers may compile successfully but fail when they execute that method.
Class declarations are commonly used when publishing JavaScript libraries to TypeScript consumers or when adding types to external JavaScript code that cannot be changed directly.
6. Ambient Module Declarations
An ambient module declaration describes a module that exists outside the current TypeScript source but does not provide suitable type declarations. It is commonly used to describe JavaScript libraries or other modules that TypeScript cannot type-check directly.
// legacy-library.d.ts
declare module "legacy-library" {
export function initialize(): void;
export function getVersion(): string;
}
TypeScript can then recognize imports from that module:
// app.ts
import {
initialize,
getVersion
} from "legacy-library";
initialize();
console.log(getVersion());
The declaration gives TypeScript a description of the module's public API. The real package or runtime module must still exist and provide the declared functions.
Ambient module declarations are especially useful for untyped JavaScript dependencies, custom runtime modules, and packages that do not supply appropriate declarations.
Keep these declarations as precise as the available evidence allows. A broad declaration that marks every function as any suppresses useful type checks and reduces the benefits of TypeScript.
7. Declaring Global Variables and Functions
Some applications rely on global values supplied by a browser script, an external library, or a runtime environment. Declaration files can describe those globals so TypeScript recognizes them.
// globals.d.ts
declare const platformVersion: string;
declare function formatPlatformName(name: string): string;
If these declarations are included in the TypeScript project, a source file can reference the names:
// app.ts
console.log(platformVersion);
console.log(formatPlatformName("IgKnight"));
These examples assume that the runtime actually provides both the variable and the function. The declaration file only tells TypeScript that they are expected to exist.
In larger applications, it is important to control where global declarations are available. A global name can create collisions with other libraries or hide dependencies that would otherwise be visible through explicit imports.
When extending global declarations from a declaration file that is treated as a module, TypeScript may require an appropriate declare global block. The correct form depends on whether the file is a script-style declaration file or an external module.
8. Using Declaration Files for Third-Party Libraries
TypeScript projects frequently use JavaScript packages installed through npm. Many popular packages provide their own declaration files, while others rely on separately maintained type packages.
When a package includes compatible declarations, TypeScript can usually use them automatically. If a JavaScript package lacks types, check whether a suitable declaration package is available before creating a local declaration file.
// example-library.d.ts
declare module "example-library" {
export interface Options {
uppercase?: boolean;
}
export function formatText(
value: string,
options?: Options
): string;
}
The declaration describes a library that exports an Options interface and a formatText function. TypeScript can use the interface to check the optional options argument and the function's return value.
This declaration is illustrative. The actual library must provide the described API. Do not copy these signatures for a different package unless they match its implementation and supported public interface.
When maintaining third-party declarations, pay attention to package versions. A declaration that describes an older API may be incompatible with a newer JavaScript implementation.
9. Declaration Files and tsconfig.json
TypeScript compiler options control how declaration files are found, included, and generated. Understanding these settings helps when a project cannot find an existing declaration or when a library needs to publish its own types.
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noEmit": true
},
"include": [
"src/**/*",
"types/**/*.d.ts"
]
}
The include setting explicitly includes application source files and declaration files stored in the types directory. This can be useful when custom declarations are kept outside src.
Many projects discover declaration files through imports or installed package metadata without listing each declaration explicitly. Custom files still need to be part of the relevant TypeScript project, either through inclusion or another supported resolution path.
The moduleResolution setting should match the runtime and build system. The Bundler setting in this example is intended for a compatible bundler-based project; Node.js applications may need NodeNext or another appropriate configuration.
If a declaration appears to be ignored, check which tsconfig.json the compiler or editor is using and confirm that the file is included in that project.
10. Generating Declaration Files from TypeScript
Declaration files do not always have to be written manually. TypeScript can generate .d.ts files from TypeScript source code during compilation. This is particularly valuable when creating libraries that should expose type information to other projects.
// src/calculator.ts
export function add(
first: number,
second: number
): number {
return first + second;
}
export interface CalculationResult {
value: number;
successful: boolean;
}
A library project can enable declaration generation in tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"declaration": true,
"outDir": "dist",
"strict": true
},
"include": ["src/**/*"]
}
When TypeScript emits the project, it can generate JavaScript output and declaration files for the exported API. The declarations contain the public type information required by consumers.
For a build that only needs declaration output, declaration-only emission is also available through emitDeclarationOnly, typically combined with declaration generation and an appropriate build workflow.
Generated declarations are generally preferable to manually maintaining duplicate signatures for a TypeScript library. They help keep the published types synchronized with the source code as the implementation changes.
11. Declaration Files for JavaScript Projects
Declaration files are also useful when documenting a JavaScript codebase that cannot immediately be rewritten in TypeScript. A JavaScript implementation can remain unchanged while a corresponding declaration provides a type-safe contract to TypeScript consumers.
// formatter.js
export function formatCourseName(name) {
return name.trim().toUpperCase();
}
// formatter.d.ts
export declare function formatCourseName(
name: string
): string;
TypeScript consumers can use the declaration to check calls to formatCourseName, even though the actual implementation is written in JavaScript.
This approach supports gradual migration because a team can add type information before converting the underlying implementation. It also makes it easier to expose a typed API from legacy modules or external code.
Declaration files and JSDoc have different maintenance trade-offs. A declaration file separates the contract from the JavaScript source, whereas JSDoc places type information alongside the implementation. Choose the approach that fits the codebase and how frequently the implementation changes.
12. Module Augmentation
Module augmentation allows you to extend the type declarations of an existing module. It can be useful when a library supports plugin behavior or when an application adds properties to an object defined by an external package.
For example, an application may augment an existing library's interface to describe a property added by a plugin.
// library.d.ts
export interface ApplicationContext {
appName: string;
}
// application-augmentation.d.ts
import "./library";
declare module "./library" {
interface ApplicationContext {
userId?: number;
}
}
The augmentation adds an optional userId property to the existing ApplicationContext interface. TypeScript can then recognize both appName and userId when checking compatible objects.
This example describes type augmentation only. If the application's runtime objects need a userId property, the implementation must actually add or provide that property.
Module augmentation should be used carefully. The augmented module must be resolved correctly, the original declaration must support augmentation, and the runtime implementation must remain compatible with the expanded type.
13. Common Declaration File Errors
Duplicate declarations
Two declaration files may define conflicting global names or incompatible versions of the same API. Review the included files, installed type packages, and declaration scopes to locate the conflict.
Cannot find declaration file
Verify that the package includes types, that the appropriate declaration package is installed if necessary, and that the active module-resolution strategy can locate the declaration entry point.
Declaration does not match implementation
A declaration may promise a function, property, or return type that the runtime does not provide. Keep declarations synchronized with the actual JavaScript implementation and library version.
Using implementation syntax inside a declaration file
Declaration files describe APIs rather than implement them. Functions normally use signatures without bodies, while classes describe their members without providing method implementations.
Declaring globals that do not exist
A declaration can make an unknown name acceptable to the compiler without creating the corresponding runtime value. Confirm that the script, library, or runtime really supplies each declared global.
Generated declarations are missing from a package
Verify the declaration compiler options, the build process, the output directory, and the package files included when publishing. Check that package metadata points to declarations that actually exist.
Best Practices for Declaration Files
- Use declaration files to describe existing runtime APIs instead of duplicating their implementations.
- Keep declared parameter types, return types, properties, and exports consistent with the real code.
- Prefer precise types over any so consumers receive useful static checking.
- Use import type when importing interfaces or type aliases only for compile-time checking.
- Generate declarations automatically for TypeScript libraries when possible.
- Keep custom declaration files included in the appropriate TypeScript project.
- Use ambient module declarations for genuinely untyped external modules.
- Apply module augmentation only when the original API supports the extension and the runtime agrees with it.
- Verify declaration output and package metadata before publishing a library.
- Remember that declaration files do not validate runtime data or create the values they describe.
Conclusion
TypeScript declaration files provide a way to describe the types and public interfaces of existing code without implementing its runtime behavior. They are essential for typed JavaScript libraries, third-party package declarations, global APIs, module augmentation, and the distribution of reusable TypeScript libraries.
Learn to write accurate .d.ts signatures, understand ambient declarations, configure declaration discovery, and generate declarations from TypeScript source when publishing libraries. Correct declarations make code easier to integrate, but they must always reflect the real runtime API to provide reliable type safety.