TypeScript · Types that pay for themselves

What are declaration files and when do you write one?

Mediumdeclaration-filesambient-typespackagesUpdated Oct 2026
Quiz this track

Short answer

Declaration files (.d.ts) describe the types of JavaScript code without emitting runtime code. They let TypeScript check imports from packages or global scripts that have no built-in types.

A declaration file contains type information only. It tells the compiler what a module or global value looks like so imports and calls can be checked. Declaration files are generated automatically when a TypeScript package is compiled, but you write them by hand for untyped JavaScript packages or global scripts.

ts
export {};

declare module "legacy-widget" {
  export function mount(element: HTMLElement): void;
  export function unmount(): void;
}

declare global {
  interface Window {
    analytics?: { track(event: string): void };
  }
}

Where declarations come from

  • The package itself may ship .d.ts files
  • The DefinitelyTyped project publishes @types packages
  • You can write an ambient declaration for an internal or untyped module
  • tsconfig types and typeRoots control which global declarations are included
  • Module augmentation extends an existing package's types without forking it

A declaration must match the runtime behavior. If the declaration says a function returns a string but the implementation returns undefined, the compiler will happily allow code that crashes. Keep hand-written declarations small and cover only the API you actually use.

Prefer an official or @types package when one exists. A local declaration can drift from the real library and is easy to forget during upgrades.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How is a .d.ts file different from a .ts file?
  2. 2What is module augmentation?
  3. 3Where does TypeScript look for global declarations?
  4. 4Why must a declaration match the runtime implementation?

Say it in the interview

A declaration file describes types for JavaScript that already exists. I use it to type an untyped package or a global script without rewriting the implementation. The declarations must match the runtime behavior, otherwise the compiler gives false confidence. I keep them close to the package or in a types folder and make sure tsconfig includes them.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.