Declaration Files (.d.ts)

Typing pure JavaScript code.

TypeScript3 min readConcept 49 of 54

The Type Overlay

A declaration file (.d.ts) is a TypeScript file that contains only type information—no actual executable JavaScript code.

It acts as a "type overlay" or a blueprint that describes the shape of pure JavaScript code to the TypeScript compiler.

The Untyped Wild West

If you install a pure JavaScript library (like an old version of lodash) and try to import it, TypeScript will throw an error because it has no idea what functions exist inside that library.

By creating a .d.ts file, you can "ambiently declare" the types for that library, allowing you to use it safely in TypeScript.

Syntax

typescript // In a file named 'global.d.ts' // 1. Typing a missing JS module declare module "untyped-lib" { export function doMagic(input: string): number; } // 2. Typing a global window variable declare global { interface Window { ANALYTICS_ID: string; } }

Try it

See how an ambient declaration file bridges the gap between an untyped JavaScript module and a strict TypeScript consumer.

// Our main.ts file
import { doMagic } from "untyped-lib";

// TS knows this returns a number thanks to .d.ts!
const result: number = doMagic("hello");
The Type Bridge
node_modules/untyped-lib/index.js
export function doMagic(str) {
  return str.length;
}
Untyped. TS compiler cannot read this file.
types/global.d.ts
declare module "untyped-lib" {
  export function doMagic(input: string): number;
}
Ambient Declaration. Acts as a blueprint for the JS file.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary purpose of a `.d.ts` file?

Remember this

  • .d.ts files contain ONLY types. No executable code.
  • Use declare module "name" to type a missing NPM package.
  • Use declare global to add types to the window object.
  • Always check for @types/package-name before writing your own!

Done with this concept?

Mark it complete to track your progress. No login needed.