Declaration files
Overview
When you import express from "express", how does TypeScript know what express() returns? The package is plain JavaScript. The answer is declaration files — .d.ts files that contain only type information. You’ll mostly consume them, but knowing how they’re found and how to write a simple one gets you unstuck whenever a package has no types.
What a .d.ts file looks like
A declaration file has types and declare statements, but no implementations:
// math.d.ts
export declare const PI: number;
export declare function circleArea(radius: number): number;
export interface Point {
x: number;
y: number;
}declare means “this exists at run time, somewhere else — here is its type”. TypeScript uses the file for checking and emits nothing for it.
You’ve been using declaration files all along: hover over console.log and press F12, and you’ll land in lib.dom.d.ts or @types/node. That’s where every built-in API gets its type.
Where package types come from
-
Bundled types. Most modern packages are written in TypeScript or ship a
.d.tsfile. Their package.json has a"types"field or"types"conditions in"exports". Nothing to install. (npmjs.com shows a blue TS badge on such packages.) -
DefinitelyTyped. For popular JavaScript packages without bundled types, the community maintains types in the DefinitelyTyped repository, published as
@types/<name>:Terminal npm install -D @types/expressnpm shows a white DT badge when such types exist. Since TypeScript 6,
@typespackages are no longer loaded automatically for global types — list global ones such asnodein tsconfig’s"types"array. Packages youimportare still found automatically. -
Your own declaration, when neither exists (below).
If TypeScript finds nothing, an import of an untyped package is an error under strict mode:
error TS7016: Could not find a declaration file for module 'some-lib'. '/project/node_modules/some-lib/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/some-lib` if it exists or add a new declaration (.d.ts) file containing `declare module 'some-lib';`Typing your own JavaScript files
For a local JavaScript file legacy-stats.js, put a legacy-stats.d.ts next to it. When you import ./legacy-stats.js, TypeScript picks up the declaration automatically:
// legacy-stats.d.ts
export declare function mean(values: number[]): number;
export declare const VERSION: string;// main.ts
import { mean } from "./legacy-stats.js";
mean([1, 2, 3]); // ✓ typed
mean("1,2,3");
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number[]'.TypeScript trusts the declaration — it can’t check that the JavaScript really behaves that way, so keep the two in sync. (The next lesson shows another approach: JSDoc types inside the .js file itself.)
declare module: typing a package
For an untyped npm package, declare the module by name in any .d.ts file included in your project:
// src/types/some-lib.d.ts
declare module "some-lib" {
export function format(value: number, pattern: string): string;
}The quick escape hatch is a declaration with no body, which types the whole module as any:
declare module "some-lib";That silences TS7016 but gives you no checking — use it as a temporary measure only.
declare module is also how you type non-code imports that a bundler handles, such as images and CSS modules:
declare module "*.svg" {
const url: string;
export default url;
}(Vite’s client types already include declarations like this.)
declare global
To add something to the global scope — a property set by a script tag, a global injected by a test runner — use declare global inside a module:
// src/globals.d.ts
declare global {
var APP_NAME: string; // globalThis.APP_NAME
interface Window {
analytics: { track(event: string): void }; // window.analytics
}
}
export {}; // makes this file a module, which declare global requiresInterfaces like Window merge with the existing declaration (Interfaces and type aliases), which is exactly what declaration merging is for. Use var for global variables — let and const don’t create properties on globalThis.
Generating declarations
When you publish a library written in TypeScript, tsc generates .d.ts files for you with the declaration option — you never write them by hand. Building and publishing covers that.
skipLibCheck
By default TypeScript type-checks every .d.ts file in your project, including thousands in node_modules. skipLibCheck: true skips checking declaration files (they’re still used), which speeds up builds and avoids errors in libraries you can’t fix. It’s in almost every real tsconfig, including tsc --init’s.
Remember:
.d.tsfiles describe JavaScript. Look for bundled types first, then@types/…, and write a small declaration (next to the file, or withdeclare module) only when neither exists.
Type an untyped JavaScript module
Your project has a legacy JavaScript file, src/legacy-stats.js (in the starter), with no types. Write src/legacy-stats.d.ts next to it that declares: mean(values: number[]): number, median(values: number[]): number, histogram(values: number[], bucketSize: number): Record<string, number>, and a constant VERSION: string. Also create src/globals.d.ts that declares a global APP_NAME: string (with declare global and var). In src/main.ts, set globalThis.APP_NAME, import the functions from ./legacy-stats.js, and print the app name, the mean, the median and the histogram of the scores. Show with // @ts-expect-error that mean("1,2,3") is now rejected.
// ---- src/legacy-stats.js (given, don't change) ----
export const VERSION = "1.4.0";
export function mean(values) {
return values.reduce((a, b) => a + b, 0) / values.length;
}
export function median(values) {
const s = [...values].sort((a, b) => a - b);
const mid = Math.floor(s.length / 2);
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
}
export function histogram(values, bucketSize) {
const buckets = {};
for (const v of values) {
const start = Math.floor(v / bucketSize) * bucketSize;
const key = `${start}-${start + bucketSize - 1}`;
buckets[key] = (buckets[key] || 0) + 1;
}
return buckets;
}
// ---- src/legacy-stats.d.ts ----
// ---- src/globals.d.ts ----
// ---- src/main.ts ----// ---- src/legacy-stats.d.ts ----
/** The library version. */
export declare const VERSION: string;
/** The arithmetic mean. Returns NaN for an empty array. */
export declare function mean(values: number[]): number;
/** The middle value (or the average of the two middle values). */
export declare function median(values: number[]): number;
/** Counts values per bucket, keyed like "70-79". */
export declare function histogram(values: number[], bucketSize: number): Record<string, number>;
// ---- src/globals.d.ts ----
declare global {
var APP_NAME: string;
}
export {};
// ---- src/main.ts ----
import { histogram, mean, median, VERSION } from "./legacy-stats.js";
globalThis.APP_NAME = "Grade Report";
const scores = [72, 85, 91, 64, 78, 88, 95];
console.log(`${APP_NAME} (stats ${VERSION})`);
console.log("mean", mean(scores).toFixed(1), "median", median(scores));
console.log(histogram(scores, 10));
function rejected() {
// @ts-expect-error -- the declaration requires an array of numbers
return mean("1,2,3"); // inside a function that never runs: it would crash
}Summary
- A
.d.tsfile contains only types — it describes JavaScript that lives elsewhere. - Libraries ship types in their package (look for “types” in package.json), or the community publishes them as
@types/name. - For untyped local JavaScript, put
name.d.tsnext toname.js; for untyped packages, usedeclare module "name". declare globaladds to global types, such as a property onwindoworglobalThis.skipLibCheck: truestops TypeScript re-checking every library’s.d.ts, which speeds builds up.