CodePark/ questions / Modules, .d.ts & tsconfig
START PRACTICINGPRACTICE
Frontend question · TypeScript › Modules, .d.ts & tsconfig

What are .d.ts files and the declare keyword for? How do you add a property to a third-party module's types or to window?

// types/env.d.ts
declare global {
  interface Window {
    analytics?: { track(event: string): void };
  }
}

declare module "some-lib" {
  interface Options {
    retries?: number;
  }
}

export {};

A .d.ts file holds only type declarations, no runtime code. declare tells TypeScript that something exists at runtime, without giving its code. To add properties, use declare module for a library and declare global for window.

A .d.ts file describes JavaScript that exists somewhere else. For example:

  • a library without built-in types (types often come from @types packages)
  • globals that a script adds to the page
  • non-code imports, such as CSS modules

Example of declare: declare const API_URL: string says that API_URL exists, without defining it.

To extend existing types, you rely on interface declaration merging: two interfaces with the same name combine into one.

  • Module augmentation uses declare module "some-lib" inside a file that is itself a module. It adds members to an interface that the library exports.
  • For globals such as Window, use declare global in a module file.

The export {} line makes the file a module. Both forms need this.

Finally, the tsconfig must include the file.

  • A .d.ts file holds types only and describes JavaScript that exists somewhere else.
  • declare says something exists at runtime without giving its code.
  • declare module adds members to a library's exported interfaces.
  • declare global extends globals like Window.
  • Augmentation relies on interface merging and must be in a module file, for example with export {}.