Declaration files

Topic 2 of 3 in Modules and declarations7 min readIntermediateFree course

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:

TypeScript
// 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

Where do the types for a package come from? For import { format } from “some-lib”;, TypeScript looks in order: 1, the package’s own types — “types” or “exports” in its package.json pointing to index.d.ts, as in most modern packages; 2, DefinitelyTyped — npm install -D @types/some-lib, community-maintained .d.ts files; 3, your own declaration — declare module “some-lib” { … } in a .d.ts file in your project. If nothing is found: error TS7016: Could not find a declaration file for module ‘some-lib’. A .d.ts file contains only types — no code. It describes JavaScript that lives somewhere else.

  1. Bundled types. Most modern packages are written in TypeScript or ship a .d.ts file. 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.)

  2. 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/express

    npm shows a white DT badge when such types exist. Since TypeScript 6, @types packages are no longer loaded automatically for global types — list global ones such as node in tsconfig’s "types" array. Packages you import are still found automatically.

  3. Your own declaration, when neither exists (below).

If TypeScript finds nothing, an import of an untyped package is an error under strict mode:

Text
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:

TypeScript
// legacy-stats.d.ts
export declare function mean(values: number[]): number;
export declare const VERSION: string;
TypeScript
// 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:

TypeScript
// 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:

TypeScript
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:

TypeScript
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:

TypeScript
// 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 requires

Interfaces 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.ts files describe JavaScript. Look for bundled types first, then @types/…, and write a small declaration (next to the file, or with declare module) only when neither exists.

Exercise

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.

TypeScript
// ---- 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 ----

Summary

  • A .d.ts file 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.ts next to name.js; for untyped packages, use declare module "name".
  • declare global adds to global types, such as a property on window or globalThis.
  • skipLibCheck: true stops TypeScript re-checking every library’s .d.ts, which speeds builds up.