Declaration Files (.d.ts)

A file that describes the shape of existing JavaScript code, with no implementation, so TypeScript can check code that uses it.

What is it?

Much of the JavaScript ecosystem (older libraries, many npm packages, your team's old code) is plain .js with no types. Import it into a TypeScript project and the compiler can't know the shape of its functions, objects and exports, so everything from it is effectively any.

A declaration file, ending in .d.ts, describes the shape of that JavaScript (each exported function's signature, each exported object's structure) with no logic at all. It's pure type information, so the compiler can check code using the library as if it were a typed TypeScript module.

You'll see them in two ways:

  • Many popular libraries ship their own .d.ts files.
  • For libraries that don't, the community-maintained DefinitelyTyped project publishes separate @types/<package-name> packages with hand-written declarations.

Explain like I'm 10

A declaration file is like an appliance's spec sheet, sold separately. It lists every button, what each accepts and what it outputs, but none of the wiring. TypeScript reads the spec sheet to check you're using the appliance correctly, even though someone else built it in a different factory.

Examples

Describing an existing JavaScript module

// mathUtils.js — a plain JavaScript file, no types
function double(x) {
  return x * 2;
}

module.exports = { double };

Ordinary untyped JavaScript. Imported into TypeScript with no declaration file, double is any, so a mistaken call like double("5") isn't caught.

A matching declaration file

// mathUtils.d.ts — describes mathUtils.js, contains no implementation
declare function double(x: number): number;

export { double };

With this file next to mathUtils.js, TypeScript can type-check every import of mathUtils as if it were written in TypeScript, while the logic stays in the .js file.

How it works

A .d.ts file uses declare to describe things that exist elsewhere at runtime (functions, variables, classes, whole modules) without implementing them.

When you import a .js file with a matching .d.ts nearby (or an installed @types/<package> package), the compiler reads the declaration file and checks your usage against it. The .d.ts file produces no JavaScript; the code that runs is still the real .js file.

Why does it exist?

Without declarations, TypeScript's checking would stop at every untyped JavaScript dependency, and every import from it would be any. Declaration files attach types to existing JavaScript without rewriting it, so checking reaches the whole dependency graph, not just your TypeScript code.

When to use it

Write a declaration file for a JavaScript library that has no types and no @types/ package. Describe just enough of its shape for your code to be checked.

You'll also see (and sometimes read or tweak) generated declaration files when publishing your own TypeScript library, so users get type checking without your original source.

When not to use it

Don't hand-write one for a library that already ships types or has a well-maintained @types/ package. Check first: duplicate or conflicting declarations cause confusing errors.

Also don't write one just to silence errors in code you plan to migrate to TypeScript. Converting the source is usually better long-term than describing it from the outside forever.

Common mistakes

  • Putting implementation logic in a .d.ts file. Declaration files are type-only; any code in them is not what runs.

  • Not checking whether a library already ships types (look for a types or typings field in its package.json) before writing or installing a redundant declaration.

  • Letting a hand-written .d.ts drift from the real JavaScript, so TypeScript confidently checks against the wrong shape.

Practice exercises

  1. Easy:

    Given function add(a, b) { return a + b; } in plain JavaScript, write a .d.ts declaration that takes two numbers and returns a number.

  2. Medium:

    Pick (or imagine) a small npm package with no built-in types. Write out how you'd install its @types/ package with npm, and why that gives you full type checking on import.

  3. Hard:

    Write a declaration file for a small JavaScript module that exports an object with nested methods (e.g. logger.info(msg) and logger.error(msg)), using declare module or declare namespace.

Interview questions

What is a `.d.ts` file?

A declaration file describing the types of existing JavaScript (functions, variables, classes, modules) with no implementation, so TypeScript can check code that uses it.

What is DefinitelyTyped, and what are `@types/` packages?

DefinitelyTyped is a community-maintained repository of declaration files for JavaScript libraries without their own types. They're published as separate @types/<package-name> npm packages you install alongside the library.

Does a `.d.ts` file produce any JavaScript when compiled?

No. It's type information only, with no runtime logic and no JavaScript output.

What does `declare module "some-module"` do, and when would you reach for it?

It's an ambient module declaration: it describes a whole module by name. Use it for a library with no .d.ts and no file to attach declarations to. Whatever is declared inside becomes the type of imports using that exact specifier.

How would you give TypeScript a type for `import logo from "./logo.png"` in a project that doesn't natively understand image imports?

A wildcard ambient module: declare module "*.png" { const src: string; export default src; }. * matches any specifier ending in .png, and the default import is a string (the asset URL the bundler produces at build time).

What makes a `.d.ts` file a global (ambient) script versus a module?

A top-level import or export. With one, the file is a module: its declarations are scoped to it and must be imported. With neither, it's a global script and everything it declares is available project-wide with no import.

You added a global-style `declare const API_URL: string;` inside a file that also has an `export` statement elsewhere, and now other files can't see `API_URL` without importing it. Why?

Any top-level export (or import) makes the whole file a module, scoping every declaration to it. To keep API_URL global, put it in a file with no top-level import/export, or wrap it in declare global { ... }.

How do you add ambient/global declarations from inside a file that's otherwise a module?

Wrap them in declare global { ... }. The file stays a module for its exports but also adds to the global scope. It's often used to extend the global Window interface.

How does TypeScript find the `.d.ts` files for a third-party package that doesn't ship its own types?

From a separately installed @types/<package-name> package under node_modules/@types (e.g. npm install --save-dev @types/lodash). By default TypeScript includes everything under @types automatically, with no import needed.

If a package ships its own types, how does TypeScript know which file to load?

It reads the types (or older typings) field in the package's package.json. If that's missing, it looks for a .d.ts file named after the package's main entry point.

You install a package whose `@types/<name>` version doesn't match the actual installed package version — what problems can that cause?

The types may describe signatures, options or exports that don't exist in your version, or miss ones that do. You get false compile errors on fine code, or worse, code that compiles but crashes at runtime because the real API differs.

What is a triple-slash reference directive, and when is it still needed?

A special comment at the top of a file, /// <reference path="..." /> or /// <reference types="..." />, that tells the compiler to include another declaration file or @types package first. It's used to connect older global .d.ts files without import/export, or to pull in ambient types not picked up automatically.

What does `export = ` mean inside a declaration file?

It describes a CommonJS module whose whole export is a single value, like module.exports = something. It lets TypeScript type import foo = require("foo") (or a default import with esModuleInterop) correctly, which export default can't represent for that shape.

What's the difference between `declare namespace Foo { ... }` and `declare module "foo" { ... }`?

declare module "foo" describes a module you import by that exact specifier. declare namespace Foo declares a global grouping (Foo.Bar, Foo.Baz) used by name with no import, for older global-script libraries.

How would you describe a JS module that exports an object with nested methods, like `logger.info(msg)` and `logger.error(msg)`?

An interface for the shape, exported as the module's export: interface Logger { info(msg: string): void; error(msg: string): void; } declare const logger: Logger; export default logger;, matching how the real module exports it.

What does the `skipLibCheck` compiler option do, and why do many projects enable it?

It skips type-checking inside all .d.ts files (yours and dependencies'), only reading the shapes they describe. Projects enable it because they can't fix errors in third-party declarations, and checking them on every build is slow.

A hand-written `.d.ts` for an internal JS module has fallen out of sync with the real implementation — what's the actual risk, versus a `.ts` file being wrong?

In a .ts file, the compiler checks the implementation against its types, so mismatches are caught. A hand-written .d.ts has no such check; the compiler just trusts it, so callers get wrong types that only show up as runtime bugs.

How does `declare function double(x: number): number;` differ from writing that same signature with a real function body in a `.ts` file?

The declare version has no body and can't have one. It only asserts that a function with this signature exists at runtime, usually in a paired .js file. The .ts version declares the type and provides the implementation compiled to JavaScript.

Why can a `.d.ts` file for a library be written and published independently from that library's actual source code?

Declaration files have no logic; the compiler only needs them for type checking, never at runtime. So others, like DefinitelyTyped contributors, can write and maintain types for a library's public API without access to its source.

If a library ships its own `.d.ts` files and an outdated `@types/<name>` package also exists for it, which does TypeScript actually use?

The package's own types (via the types field in its package.json). A leftover @types package is usually stale; remove it to avoid confusion or, more rarely, real declaration conflicts.

If a `.d.ts` file's `declare function double(x: number): number;` doesn't match what the real `mathUtils.js` actually does at runtime (say it really returns a string), what will TypeScript report?

Nothing. TypeScript never looks at what mathUtils.js really does; it trusts the declaration. Callers are checked against the promised number, so the problem is silent at compile time and only appears at runtime.

How does an `@types` package differ from a library shipping types in its own package alongside its code?

An @types package is maintained separately (usually by DefinitelyTyped contributors, not the library's authors) and installed on its own, so it can drift from the library's version. Types shipped inside the library are maintained by its authors and versioned with the code, so they're usually more accurate.