Sub topic 9
Declaration files: describing code without implementing it
This chapter assumes you can write TypeScript types, interfaces, and functions. It also assumes you can run tsc and edit tsconfig.json. You should know how import and export work, and what a package.json is. Here you learn what a declaration file is and how the compiler reads one. Later chapters cover ambient declarations, @types packages, augmentation, and publishing.
What a declaration file is
A declaration file ends in .d.ts. It contains only type information: signatures, interfaces, type aliases, and the shapes of values. It has no function bodies and no runtime code. The compiler reads it to learn what a piece of JavaScript looks like. It never emits JavaScript for it.
Declaration files exist because JavaScript carries no types. When your TypeScript imports a library written in plain JavaScript, the compiler needs a description of that library. The .d.ts file supplies it. The implementation stays in a .js file, and the description lives next to it.
The pairing looks like this:
| File | Holds | Read by |
|---|---|---|
| `index.js` | The running code | Node.js, the browser, or a bundler |
| `index.d.ts` | Types for that code | The TypeScript compiler and editor |
| `index.ts` | Code and types together | The TypeScript compiler, which emits both of the files above |
Reading a declaration file
A declaration file looks like a TypeScript file with the implementations removed. These rules apply:
- Functions have a signature and no body.
- Top-level declarations in a module file use
export. They may also carrydeclare, which says "this exists at runtime, and I am only describing it". - Variables have a type annotation and no initializer, except for
constdeclarations with a literal type. - Classes list their members with types and no method bodies.
- Interfaces and type aliases look the same as in
.tsfiles, because they are already types only.
Here is a small declaration file for a hypothetical slugify helper:
// slugify.d.ts
export interface SlugOptions {
separator?: string;
lowercase?: boolean;
}
export declare function slugify(input: string, options?: SlugOptions): string;
export declare const VERSION: string;
export declare class Slugger {
constructor(options?: SlugOptions);
slug(input: string): string;
}A consumer imports from it the way it would import from any module:
import { slugify, Slugger } from "./slugify.js";
console.log(slugify("Hello World", { separator: "_" }));
console.log(new Slugger().slug("Another Title"));The compiler checks these calls against the declarations. If you pass a number to slugify, you get an error. The compiler does not check that the matching .js file really exports these names. A declaration file is a claim, and the compiler trusts it.
Declaration files are a trust boundary
Since the compiler trusts a .d.ts file, a wrong declaration produces a runtime failure that the type checker cannot see. Suppose slugify.d.ts says slugify returns string, but the JavaScript returns undefined for empty input. Your code type-checks and then fails when it calls .length on undefined.
Keep these points in mind:
- A missing export in the
.jsfile still compiles if the.d.tsfile declares it. - A declaration that is too narrow rejects valid calls.
- A declaration that is too loose, such as
any, lets bad calls through. - Types from a
.d.tsfile are only as accurate as the person who wrote them.
Module declaration files and global declaration files
The rule from the start of this tutorial applies here. A .d.ts file is a module if it has a top-level import or export. Otherwise it is a global script, and everything it declares enters the global scope.
This difference changes the meaning of the file:
// globals.d.ts (no import or export: a global script)
declare const APP_VERSION: string;
interface Window {
appConfig: { apiUrl: string };
}// module.d.ts (has export: a module)
export declare const APP_VERSION: string;In the first file, APP_VERSION is a global variable that any file in the project can use without an import. In the second file, APP_VERSION is an export that consumers must import. Adding a stray export {} to a global declaration file turns it into a module. The global names then stop being global. This is a common cause of "cannot find name" errors after an edit.
How the compiler finds declaration files
When the compiler resolves an import such as ./slugify.js, it looks for several candidates next to the path. For a .js specifier it tries the matching .ts, then .tsx, then .d.ts. Your own .ts file wins over a .d.ts file with the same base name. The .d.ts file is used when only JavaScript exists.
Two other mechanisms bring declaration files into a project:
- Resolution from an import. The compiler follows the import to a
.tsor.d.tsfile. The next chapters cover how packages take part in this. - Inclusion by
include,files, ortypeRoots. A.d.tsfile listed byincludeis part of the program even if nothing imports it. Global declarations depend on this. Aglobals.d.tsfile insidesrcis picked up by"include": ["src"].
The configuration below includes everything in src, so a global .d.ts file there applies to the whole program:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src"]
}The skipLibCheck option
The compiler type-checks every .d.ts file in the program by default. Declaration files from dependencies can conflict with each other or with your compiler settings. The skipLibCheck option tells the compiler to skip checking all .d.ts files.
{
"compilerOptions": {
"skipLibCheck": true
}
}The option has a cost. It hides errors in declaration files you wrote yourself, along with the ones from libraries. Many projects enable it to avoid noise from third-party packages. If you author declaration files, check them in a separate step, or keep the option off in the project that publishes them.
Declaration files and ES module syntax
A .d.ts file uses the same module syntax as a .ts file. Named exports, default exports, and namespace imports all work. The next listing shows a declaration for a module that has both named and default exports:
// math.d.ts
export declare function add(a: number, b: number): number;
export declare const PI: number;
declare function multiply(a: number, b: number): number;
export default multiply;The declare keyword is required on a value declaration at the top level of a .d.ts file. A function without declare or export is an error there. Types do not need it, because they never exist at runtime.
A declaration for a CommonJS module that assigns a single function to module.exports uses export =:
// greet.d.ts
declare function greet(name: string): string;
export = greet;A consumer reads it with a default import when esModuleInterop is on:
import greet from "./greet";
console.log(greet("Ada"));Without esModuleInterop, the compiler requires import greet = require("./greet") or import * as greet. The interop chapter covers the reasons.
How a declaration file relates to the emitted code
The following diagram shows which files the compiler reads and which it writes for a project that mixes TypeScript and JavaScript dependencies.
The library's .d.ts helps the checker and then disappears. At runtime only JavaScript runs.
Writing declarations for your own JavaScript
Suppose a project has a plain JavaScript file you cannot convert yet. Create a .d.ts file with the same base name beside it.
// counter.js
export function createCounter(start = 0) {
let value = start;
return {
next() {
value += 1;
return value;
},
};
}// counter.d.ts
export interface Counter {
next(): number;
}
export declare function createCounter(start?: number): Counter;A TypeScript file can now import createCounter with full checking:
import { createCounter } from "./counter.js";
const c = createCounter(10);
console.log(c.next());Two details matter here. The .d.ts file must sit beside the .js file, and the import specifier uses the .js extension. Also, allowJs is not needed for this arrangement. With allowJs on, the compiler would read the JavaScript and try to infer types, and the .d.ts file would then be ignored. Without it, the .d.ts file is the single source of types for that module.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module './x.js' or its corresponding type declarations` | No `.ts` or `.d.ts` file beside the `.js` file | Add `x.d.ts` or convert the file |
| `Top-level declarations in .d.ts files must start with either a 'declare' or 'export' modifier` | A value declared without `declare` | Add `declare` or `export` |
| A global name stops working | An `import` or `export` turned the file into a module | Remove it, or move the declaration into `declare global` |
| Runtime error on a call that type-checked | The `.d.ts` file does not match the JavaScript | Correct the declaration and test it against the real code |
| Errors inside `node_modules` types | Conflicting declaration files | Turn on `skipLibCheck`, or fix the dependency versions |
Summary of decisions
Use a .d.ts file when the implementation is JavaScript that you cannot or do not want to convert. Prefer plain .ts files for your own code, because the compiler then checks the implementation and the types together. Let the compiler generate declaration files for any package you publish, a topic covered in a later chapter. Write them by hand only when you must describe code that TypeScript did not produce.
Exercise
A project contains src/env.d.ts with the line declare const BUILD_ID: string;. A developer adds export {}; to the bottom of the file, and BUILD_ID is then reported as "Cannot find name" in other files. Why does this happen, and how can the developer keep the declaration global while the file stays a module?
Show answer
Adding export {} turns the file into a module, so BUILD_ID becomes a module-scoped declaration instead of a global one. To keep it global, wrap the declaration in declare global { const BUILD_ID: string; } inside the module file. Alternatively, remove export {} so the file is a global script again.
Exercise
You have legacy.js that exports function parse(text), which returns an array of strings. Write the legacy.d.ts file, and explain why the compiler will not catch it if parse actually returns null for empty input.
Show answer
The file is export declare function parse(text: string): string[];. The compiler trusts a declaration file and never compares it with the JavaScript implementation, so a null return at runtime is invisible to the type checker. A more honest declaration would be string[] | null.