Mastering TypeScript Declaration Files: When and How to Write .d.ts

This guide explains what TypeScript declaration (.d.ts) files are, when they’re needed, and provides step‑by‑step examples for writing global, npm‑package, and module‑augmentation declarations, plus configuration tips for automatic generation in modern JavaScript projects.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Mastering TypeScript Declaration Files: When and How to Write .d.ts

In the era of fully embracing TypeScript, .d.ts declaration files are essential for describing the type information of JavaScript modules.

Definition of Declaration Files

In TypeScript, files ending with .d.ts are called declaration files. Their main purpose is to describe the type information of all exported interfaces in a JavaScript module.

When to Write TS Declaration Files

Most of the time you don't need to write a declaration file manually. If your source is written in TypeScript, the compiler can generate .d.ts files automatically and you can publish them together.

Three situations require manual declaration files:

Third‑party libraries loaded via a <script> tag or CDN that expose global methods without TypeScript definitions.

Third‑party npm packages that do not provide their own declaration files.

Internal JavaScript libraries or plugins that you want to give a better development experience.

How to Write TS Declaration Files

Different kinds of declaration files have slightly different syntax. Remember that a declaration file only defines types; it must not contain assignments.

Global Variables

Common syntaxes for declaring globals include:

declare let/const // declare global variable
declare function // declare global function
declare class // declare global class
declare enum // declare global enum
declare namespace // declare global object with sub‑properties
interface / type // declare global types

Examples:

// variable
declare let userName: string;
declare const wx: any;

// function overloads
declare function getName(uid: number): string;
declare function getName(): string;
declare function getName(cb: () => any): any;

// class
declare class Course {
  cid: number;
  constructor(cid);
  getCoursePrice(): number;
}

// enum
declare enum Status {
  Loading,
  Success,
  Failed,
}

// interface
interface CourseInfo {
  cid: number;
  name: string;
}

// generic interface
interface CGIData<T> {
  data: T;
  retcode: 0;
}

// namespace
declare namespace User {
  interface User {
    name: string;
    age: number;
  }
  function getUserInfo(name: string): User;
  namespace fn {
    function extend(obj: any): any;
  }
}
declare function User(id: number): string; // declaration merging

npm Packages

For npm packages without declaration files, create a types directory, add your .d.ts files there, and configure tsconfig.json with appropriate baseUrl and paths:

{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl": "./", // relative path to types folder
    "paths": { "*": ["types/*"] }
  }
}

Typical export syntaxes in a declaration file are:

export const/let // export variable
export namespace // export object with sub‑properties
export default // ES6 default export
export = // CommonJS export

Extending Existing Modules or Globals

You can augment already‑declared modules or globals using declaration merging.

interface Window {
  readonly request?: any;
  readonly devToolsExtension?: any;
  readonly wx?: any;
}
declare module "querystring" {
  function escape(str: string): string;
  function unescape(str: string): string;
}

Triple‑slash references can also be used:

/// <reference path="custom.d.ts" />

Automatic Generation

To let TypeScript generate .d.ts files automatically during compilation, enable the declaration option in tsconfig.json:

{
  "compilerOptions": {
    "declaration": true
  }
}

References

TypeScript Beginner Tutorial – Declaration Files

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptnpmtype definitionsd.tsdeclaration-filestsconfig
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.