Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 96 ยท Modules and Declarations

Declaration Files (.d.ts)

Learn what TypeScript .d.ts declaration files are, how @types packages work, how to type a JavaScript library, and how declare global and augmentation work.

When you call readFileSync from node:fs in our editor, TypeScript knows its parameters and return type, even though Node.js is written in C++ and JavaScript, not TypeScript. That knowledge comes from a declaration file: a .d.ts file that describes the shape of code (its functions, classes, variables and types) without containing any implementation. Declaration files are how TypeScript understands JavaScript libraries, browser APIs, Node.js and even the JavaScript language itself.

You'll deal with declaration files in four situations: when you install a library and its types come with it (or from an @types package), when you publish your own TypeScript library, when you need types for a JavaScript library that has none, and when you add properties to a type you don't own, such as process.env or a framework's request object. This lesson covers all four, with runnable demos of the declare keyword that every declaration file is built from.

What a declaration file contains

A .d.ts file is TypeScript with only the type information left. Functions have signatures but no bodies; classes have members but no code; variables have types but no values. Here's a small JavaScript module and a declaration file that describes it:

JavaScript
// slugify.js (plain JavaScript, maybe from an old package)
export function slugify(text, separator = '-') {
  return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, separator);
}

export const VERSION = '2.1.0';
TypeScript
// slugify.d.ts (sits next to slugify.js)
export declare function slugify(text: string, separator?: string): string;
export declare const VERSION: string;

When TypeScript resolves import { slugify } from './slugify.js', it finds slugify.d.ts next to the JavaScript file and uses it for type checking. The JavaScript file is what actually runs. Nothing checks that the two agree: a declaration file is a promise about what the JavaScript does, and if the promise is wrong, your code type-checks and then fails at runtime.

Declaration files have a few rules:

  • They can't contain implementations or statements that run (console.log(...), function bodies, initial values).
  • Top-level declarations use declare (or export declare). Interfaces and type aliases don't need it, because they never have a runtime part anyway.
  • They're never compiled to JavaScript. tsc emits nothing for a .d.ts file.

The declare keyword

declare means "this exists at runtime, but somebody else provides it". You can use it in ordinary .ts files too, which lets us try it in the editor. The next program declares a global function and a global constant, the way you'd describe a <script>-tag library or a value a bundler injects:

TypeScript declare promises something exists (fails at runtime on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program type-checks, because declare gave both names a type. But declare emits no JavaScript, and nothing in this sandbox defines trackEvent, so the run prints the first line and then crashes with ReferenceError: trackEvent is not defined. That's exactly the risk of a wrong declaration. Now provide the values first, the way a script tag or a bundler would:

TypeScript Declarations backed by real values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Now the declarations match reality: both calls run, and the type checker still rejects calls that break the declared signature. (The last call shows the error is caught; because @ts-expect-error suppresses it, it also runs and prints { query: 'typescript' }, proving once more that types don't exist at runtime.)

You can declare anything that has a runtime existence:

TypeScript
declare let currentUser: { id: number; name: string } | null;
declare function format(value: number, pattern?: string): string;
declare class Chart {
  constructor(element: string, options?: { animate?: boolean });
  render(): void;
  destroy(): void;
}
declare enum Direction { Up, Down }
declare namespace Analytics {
  function track(name: string): void;
  const version: string;
}

Where declaration files come from

Types built into TypeScript

TypeScript ships with lib.*.d.ts files that describe JavaScript itself (Array, Promise, Map) and the browser (document, HTMLElement, fetch). The lib option in tsconfig.json selects them. Our editor uses lib: esnext without dom, which is why document isn't defined here (see TypeScript in the Browser).

Types bundled with a package

Most modern npm packages are written in TypeScript or ship hand-written declarations. Their package.json points to the declarations, and TypeScript picks them up automatically:

JSON
{
  "name": "tiny-dates",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  }
}

The "types" condition must come first inside each exports entry, because conditions are matched in order. Older packages use a top-level "types" field instead. If a package's page on npm shows a "TS" badge, its types are bundled.

@types packages from DefinitelyTyped

For JavaScript packages without bundled types, the community maintains declarations in the DefinitelyTyped repository, published to npm under the @types scope:

Terminal
npm install express
npm install --save-dev @types/express

TypeScript automatically includes every package in node_modules/@types unless the types option lists specific ones. Our editor compiles with --types node, so @types/node is the only one loaded: that's where readFileSync, process and Buffer get their types. Install @types/* packages as dev dependencies: they're needed only at compile time. Keep their major version in line with the library's major version (express@5 goes with @types/express@5).

Declarations you generate

When you build a TypeScript library, "declaration": true makes tsc write a .d.ts file next to each .js file it emits. Your users then get your exact types with no extra work. For example, from this source:

TypeScript
// src/math.ts
export interface Range {
  min: number;
  max: number;
}

export function clamp(value: number, range: Range): number {
  return Math.min(range.max, Math.max(range.min, value));
}

tsc generates:

TypeScript
// dist/math.d.ts
export interface Range {
    min: number;
    max: number;
}
export declare function clamp(value: number, range: Range): number;

The tooling lesson covers publishing libraries, including declarationMap (so "Go to definition" jumps to your source) and isolatedDeclarations.

Typing a JavaScript library yourself

Sometimes there are no types at all: an internal JavaScript package, or a small library nobody has typed. You have three options, from quickest to best.

1. A shorthand module declaration. One line silences "could not find a declaration file" (error TS7016) by declaring that the module exists. Everything imported from it is any:

TypeScript
// types/legacy-charts.d.ts
declare module 'legacy-charts';

It's a stopgap: you lose all checking for that library.

2. A real module declaration. Describe the parts you use. Put it in a .d.ts file that's included in your project (for example types/legacy-charts.d.ts, with "include": ["src", "types"] in tsconfig):

TypeScript
// types/legacy-charts.d.ts
declare module 'legacy-charts' {
  export interface ChartOptions {
    title?: string;
    width?: number;
    height?: number;
  }

  export interface DataPoint {
    label: string;
    value: number;
  }

  export function drawBarChart(target: string, data: DataPoint[], options?: ChartOptions): void;

  const version: string;
  export default version;
}

declare module 'name' { ... } with a quoted name is an ambient module declaration. It must live in a declaration file (or another file that isn't itself a module); inside a module file, the same syntax means augmentation, covered below.

3. Contribute the declarations to DefinitelyTyped (or to the library itself), so everybody benefits.

Wildcard modules for non-code imports

Bundlers let you import files that aren't JavaScript, such as images and stylesheets. TypeScript needs a declaration to accept those imports. Wildcards in module names cover every matching path:

TypeScript
// types/assets.d.ts
declare module '*.svg' {
  const url: string;
  export default url;
}

declare module '*.module.css' {
  const classes: Readonly<Record<string, string>>;
  export default classes;
}

Frameworks like Vite ship such declarations for you (vite/client).

declare global: adding to the global scope

Inside a module, top-level declarations are local to that module. To add something to the global scope from a module, wrap it in declare global { ... }. This is also how you extend built-in interfaces, because interfaces with the same name merge (see declaration merging):

TypeScript declare global and interface merging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few things to notice:

  • Global variables must be declared with var inside declare global; let and const declarations don't become properties of globalThis, so globalThis.APP_NAME wouldn't type-check with them.
  • interface Array<T> { last(): ... } doesn't replace the built-in Array interface; it merges a new method into it. The runtime code that actually adds the method is still your job.
  • export {} makes sure the file is a module, because declare global is only allowed in modules. (Our editor already treats main.ts as a module, but in a standalone .d.ts or .ts file without imports, you need it.)

Adding methods to built-in prototypes is risky in shared code: a future JavaScript version may add a method with the same name but different behavior (this has happened, which is why arrays have flat and not flatten). Do it only in applications, never in libraries. Extending global types for values that really exist, like process.env below, is safe.

Typing process.env

A very common, safe use of global augmentation: describing the environment variables your app reads. @types/node declares process.env with the interface NodeJS.ProcessEnv, designed to be merged:

TypeScript Typed environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

With the merge in place, process.env.APP_MODE autocompletes and has a precise union type, and comparing it with a misspelled 'prod' is a compile error (TS2367, "This comparison appears to be unintentional"). Values in the environment are always strings or missing, so declare them as optional, and still validate them at startup: the declaration doesn't make the variable exist.

Module augmentation

Module augmentation adds declarations to an existing module, the way declare global adds to the global scope. It's how plugins and middleware extend a library's types. Inside a module file, write declare module with the module's name, and add or merge interfaces:

TypeScript Augmenting node:http, Express-style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

IncomingMessage is a class from @types/node, and the class's instance interface merges with the interface in the augmentation, so req.user is now a known, typed property. Frameworks build on the same mechanism: Express users augment Express.Request, Vue plugins augment ComponentCustomProperties, Fastify plugins augment FastifyInstance.

The rules of augmentation:

  • The file must be a module (it has an import or export), and the module name must resolve to a real module, otherwise you get error TS2664, "Invalid module name in augmentation".
  • You can add new declarations and merge into existing interfaces, but you can't add new top-level exports that the JavaScript doesn't really have, or change existing types.
  • The augmentation applies to the whole program once the file is included, not just to the file that declares it.

Checking declaration files: skipLibCheck

By default, TypeScript type-checks every .d.ts file in your program, including all of node_modules/@types. Two libraries with conflicting declarations can then produce errors in files you don't control. Most projects set "skipLibCheck": true, which skips checking declaration files (your own .ts files are still fully checked against them). It also makes builds faster. Library authors should still check their own published declarations in CI.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens at runtime with declare function greet(name: string): string; and a call greet('Ada') when nothing defines greet?

    declare only tells the type checker that the function exists and emits no JavaScript. If nothing provides it at runtime, the call fails.
  2. 2. Where does TypeScript get the types for readFileSync in our editor?

    Node's APIs are described by the @types/node package. The types option selects which @types packages are loaded.
  3. 3. What does declare module 'old-lib'; (no body) in a .d.ts file do?

    A shorthand ambient module declaration silences TS7016 but gives up all checking for that module.
  4. 4. Inside declare global, why must a global variable be declared with var?

    Global let and const live in a separate scope and aren't properties of globalThis, so globalThis.NAME only type-checks for var declarations.
  5. 5. You write declare module 'node:http' { interface IncomingMessage { user?: User } } in a file with an import. What is this?

    In a module file, declare module with an existing module's name augments it. Interfaces merge, so IncomingMessage gains the user property everywhere.

Summary

  • A declaration file (.d.ts) describes the types of code without implementing it. It's a promise about runtime behavior that nothing verifies.
  • declare says "this exists at runtime, provided elsewhere" and emits no JavaScript; a wrong declaration compiles and then fails at runtime.
  • Types come from TypeScript's lib files, from packages that bundle .d.ts files (via "types" in exports), from @types/* packages (DefinitelyTyped), or from tsc with "declaration": true.
  • For untyped libraries, use a shorthand declare module 'name'; as a stopgap, or better, a full declare module 'name' { ... } in a .d.ts file. Wildcard modules ('*.svg') type asset imports.
  • declare global { ... } adds globals and merges into built-in interfaces such as Array or NodeJS.ProcessEnv.
  • Module augmentation (declare module 'lib' inside a module) merges new members into a library's interfaces, which is how plugins and middleware add typed properties.
  • skipLibCheck: true skips checking .d.ts files, avoiding conflicts in node_modules and speeding up builds.

Next: Namespaces