Writing TypeScript Declaration Files: Typing Third-Party JavaScript Libraries

Most JavaScript libraries you bring into a TypeScript project were never written with types in mind. I learned this the hard way while integrating a niche canvas rendering library that had excellent documentation but zero type support — my editor went silent, autocomplete disappeared, and every call was typed as any. Writing your own declaration files is the bridge between those untyped dependencies and the safety TypeScript promises. In my experience, the initial investment of an afternoon spent crafting accurate .d.ts files pays for itself within days through faster refactoring and fewer runtime surprises. This article walks through the process I use to type third-party JavaScript libraries from scratch, including where to put the files, how to model complex JavaScript patterns accurately, and how to keep those definitions maintainable as both your code and the library evolve.

Decoding Module Resolution: How TypeScript Locates Your d.ts Files

Before writing a single line of type definition, you need to understand how TypeScript discovers declaration files. The compiler does not magically scan your project; it follows specific resolution rules governed by your tsconfig.json. When I first started writing declarations, I placed a global.d.ts file in my project root and assumed it would be picked up everywhere. It wasn't, because my include array was too restrictive. The two options that control this are typeRoots and paths, and understanding the difference saves hours of frustrating "Cannot find module" errors.

Configuring typeRoots and baseUrl for Local Definitions

By default, TypeScript looks in node_modules/@types for declarations. If you are writing local overrides or definitions for an unpublished library, you should declare an additional type root. I typically create a ./types folder at the project root and point the compiler there:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "typeRoots": ["./node_modules/@types", "./types"],
    "baseUrl": ".",
    "paths": {
      "*": ["types/*"]
    }
  },
  "include": ["src/**/*", "types/**/*"]
}

This setup tells TypeScript to treat ./types as a first-class source of declarations. Inside that folder, I mirror the package name. For a library called canvas-helper, the structure would be types/canvas-helper/index.d.ts. The file name matters — index.d.ts inside a folder named after the package is the conventional pattern that moduleResolution: "node" expects. I have also seen teams use a single declarations.d.ts file with multiple declare module '...' blocks; that works for small projects but becomes unwieldy once you have more than two or three custom-typed libraries.

Ambient Modules Versus External Modules

A common point of confusion is the difference between ambient and external module declarations. An ambient declaration uses declare module 'library-name' and is necessary when you are providing types for a JavaScript file that TypeScript cannot otherwise analyze. An external module is a .d.ts file that itself uses top-level import or export statements and is treated as a module. In my experience, you should prefer external module files when possible. Create types/canvas-helper/index.d.ts that directly exports types, rather than wrapping everything in a declare module block. The ambient form is only required when you have a single global file aggregating many declarations or when you need to augment the global scope. If your declaration file contains no imports or exports, TypeScript treats it as a script file and its declarations become global — often not what you intended. Adding an empty export {} at the bottom is a simple trick I use to force a file to be treated as a module when it otherwise has only interface declarations.

Anatomy of an Ambient Module Declaration for Untyped Libraries

When a library ships plain JavaScript, your declaration file is the sole source of truth for its public API. I start every new declaration by reading the library's source entry point and its README, then sketching the shape before I touch TypeScript syntax. A useful mental model is to think of the .d.ts file as a header file in C: it describes the shape but contains no implementation.

For a simple library that exports a few functions and constants, the structure is straightforward. Consider a hypothetical utility library string-fns that exposes slugify and truncate as named exports and a default export that is a configuration object:

// types/string-fns/index.d.ts
export interface SlugifyOptions {
  lower?: boolean;
  strict?: boolean;
  locale?: string;
}

export function slugify(input: string, options?: SlugifyOptions): string;

export function truncate(input: string, maxLength: number, ellipsis?: string): string;

export interface StringFnsConfig {
  defaultLocale: string;
}

declare const config: StringFnsConfig;
export default config;

What matters here is precision. In the actual JavaScript implementation, slugify might accept null and coerce it to a string, but typing it as string forces callers to handle that coercion explicitly, which I've found prevents a class of bugs around unexpected empty slugs. For optional parameters, use ?: rather than unioning with undefined unless the library genuinely distinguishes between an omitted argument and an explicit undefined. I also pay close attention to whether a function is pure or mutates its input; while you cannot enforce immutability in the type system alone, marking parameters as readonly arrays or using Readonly<T> communicates intent and works well when combined with the techniques described in TypeScript Utility Types: Pick, Omit, Partial and Record Explained.

Declaring CommonJS and UMD Libraries That Lack ES Module Syntax

Many older libraries still use module.exports = ... or attach themselves to window. These require a slightly different declaration style. For a CommonJS library that does module.exports = function createWidget(options) { ... } and also attaches properties like createWidget.version, you need to use the export = syntax combined with a namespace:

// types/legacy-widget/index.d.ts
declare function createWidget(options: CreateWidgetOptions): WidgetInstance;

declare namespace createWidget {
  const version: string;
  function isWidget(value: unknown): value is WidgetInstance;
}

interface CreateWidgetOptions {
  container: HTMLElement | string;
  autoRender?: boolean;
  theme?: "light" | "dark";
}

interface WidgetInstance {
  render(): void;
  destroy(): void;
  readonly element: HTMLElement;
}

export = createWidget;

This pattern — a callable function with an attached namespace — is idiomatic for describing jQuery-style libraries and many Node utilities. The corresponding import in consuming code uses import createWidget = require("legacy-widget") or, with esModuleInterop enabled, import createWidget from "legacy-widget". Getting this interop correct is critical; I have spent time debugging why a library appeared to have no default export only to realize my declaration used export default when it should have used export =. The TypeScript handbook is clear on this distinction, and the behavior is tied to how module systems are compiled, which you can cross-reference with the ECMAScript module semantics documented on MDN Web Docs.

Bridging JavaScript Patterns to Static Types: Functions, Classes, and Hybrid Exports

JavaScript is far more flexible than the class-based type model TypeScript prefers, so the most challenging part of writing declarations is faithfully modeling dynamic patterns without resorting to any. I've found that three patterns cause most of the difficulty: overloaded functions, constructor functions that can be called with or without new, and hybrid objects that are both callable and have properties.

Function overloads in JavaScript often depend on runtime type checks. For example, a format utility might accept either a string template and values, or a configuration object. Instead of collapsing this into a single signature with unions, write explicit overloads. TypeScript resolves overloads top-down, so order them from most specific to most general:

export function format(template: string, ...args: unknown[]): string;
export function format(options: FormatOptions): string;
export function format(templateOrOptions: string | FormatOptions, ...args: unknown[]): string;

export interface FormatOptions {
  template: string;
  args: unknown[];
  locale?: string;
}

The implementation signature — the last one — is not visible to callers but must be compatible with all overloads. This approach gives you precise call-site checking and better hover documentation than a single union-based signature. When the overload set grows beyond three or four variants, consider whether generics would simplify the definition. I often reach for patterns discussed in TypeScript Generics: Practical Examples Beyond the Basics to keep these signatures DRY without losing specificity.

Typing Constructor Functions and Callable Interfaces With Properties

Some libraries export a function that acts as both a factory and a constructor. A classic example is a library where Lib() creates an instance and new Lib() does the same, but with slightly different initialization logic. You model this with a callable interface that has a construct signature:

export interface LibInstance {
  update(data: Record<string, unknown>): void;
  readonly id: string;
}

export interface LibConstructor {
  (initialData?: Record<string, unknown>): LibInstance;
  new (initialData?: Record<string, unknown>): LibInstance;
  prototype: LibInstance;
  createBatch(count: number): LibInstance[];
}

declare const Lib: LibConstructor;
export default Lib;

This declares that Lib can be invoked either way and also exposes static methods and the prototype. For hybrid exports that are functions with properties — like axios, which you can call as axios(url) but also use as axios.get(url) — the same interface pattern applies. In my experience, capturing these dual-purpose exports correctly is what separates a declaration file that merely silences errors from one that actually guides the developer toward correct usage.

Augmenting Existing Types When Declarations Are Incomplete or Inaccurate

Even when a library ships with its own .d.ts files, those types are sometimes incomplete, outdated, or overly permissive. Rather than forking the library or using // @ts-ignore throughout your codebase, you can use declaration merging and module augmentation to patch the types locally. I've used this approach to add missing options to a charting library that had documented a new animationDuration property but hadn't updated its types for two releases.

Module augmentation uses the declare module syntax inside a file that is itself a module. To augment chart-lib, create a file like types/chart-lib-augment.d.ts:

// types/chart-lib-augment.d.ts
import "chart-lib";

declare module "chart-lib" {
  interface ChartOptions {
    animationDuration?: number;
    onRenderComplete?: (chart: ChartInstance) => void;
  }

  interface ChartInstance {
    exportToImage(type: "png" | "jpeg"): Promise<Blob>;
  }
}

The initial import "chart-lib" is crucial — it tells TypeScript that this file is an augmentation of the existing module rather than a new ambient module definition that would replace it. Without that import, you will erase the original types. For global augmentations, such as adding a property to Window that a third-party script injects, you use declare global:

// types/window-augment.d.ts
export {};

declare global {
  interface Window {
    __LEGACY_APP_BRIDGE__?: {
      sendMessage(type: string, payload: unknown): void;
    };
  }
}

One risk with augmentation is that you can mask real mismatches. I make it a practice to add a comment with the library version and a link to the issue or PR where the missing type was reported, so the augmentation can be removed when upstream catches up. If the augmentation involves narrowing a type that was previously string to a more specific union, consider whether Discriminated Unions in TypeScript: Modeling Domain Logic Safely offers a better model for the corrected shape, especially when the library uses tagged objects internally.

Structuring and Publishing Declaration Files for Long-Term Maintainability

A declaration file is code, and it needs the same attention to organization and maintenance as implementation code. When I started, I put everything in one index.d.ts and quickly ended up with a 900-line file that was difficult to navigate. I now split declarations by feature area, even for a single library. For a moderate-sized library called data-grid, the structure might look like this:

types/data-grid/
├── index.d.ts          // re-exports public API
├── column.d.ts         // column definitions
├── row.d.ts            // row and cell types
├── events.d.ts         // event handlers
└── utils.d.ts          // internal helpers re-exported for advanced users

The index.d.ts file then re-exports the public surface:

// types/data-grid/index.d.ts
export * from "./column";
export * from "./row";
export * from "./events";
export { DataGrid } from "./grid";

This mirrors how well-structured projects organize source code, and it makes pull requests that update types much easier to review. Keep the public API narrow — do not export helper types that are not part of the library's documented interface unless you have a clear reason and mark them as internal with JSDoc @internal. Add TSDoc comments to every exported function and interface; editor tooltips are the primary way developers consume these types, and a one-line description prevents them from having to switch back to external documentation.

When your declarations are mature, you have three distribution options. The table below summarizes the tradeoffs I have encountered when deciding how to share them:

Distribution Method When to Use Maintenance Cost Consumer Setup
Bundled with library (ships in package) Library author controls types Low — versioned with code Zero config
Separate @types package via DefinitelyTyped Third-party types for popular libraries Medium — external review process npm install @types/name
Local ./types folder in consuming project Internal or niche libraries High — manual sync required Configure typeRoots/paths
Inline JSDoc with allowJs + checkJs Gradual migration, no build step Medium — types live in JS files Enable checkJs flag

If you maintain a library internally, I recommend bundling the .d.ts files with the package and setting the "types" field in package.json. This eliminates drift between implementation and types. For public libraries you do not own, contributing to DefinitelyTyped is the best long-term option, but keep a local copy in your ./types folder until the contribution is merged. I have found that adding a small type test file using tsd or expect-type catches regressions before they reach consumers. Those tools let you assert that certain assignments should or should not compile, which is invaluable when the library's runtime behavior is loosely documented.

Handling Dynamic Runtime Behavior That Defies Static Typing

Some JavaScript libraries lean heavily on runtime dynamism — string-based property access, plugin systems that mutate prototypes, or configuration objects where the presence of one key changes the type of another. Trying to type these with 100% accuracy can lead to overly complex definitions that are harder to use than a simple any. The goal is not perfection but a practical balance between safety and usability.

For string-based APIs like a library that does db.get('users.0.name') with dot-notation paths, you can use template literal types to provide a degree of safety without modeling every possible path. In my experience, a simple overload that handles the common cases plus a fallback is more helpful than a fully generic path parser that produces unreadable error messages:

export interface DB {
  get<K extends keyof DataSchema>(key: K): DataSchema[K];
  get(path: string): unknown;
  get<T = unknown>(path: string): T;
}

For plugin systems that extend an instance at runtime — for example, app.use(plugin) adds app.pluginMethod() — you cannot type the mutation directly. Instead, type the plugin registration function to return an intersection type, and encourage consumers to capture the returned value:

export interface App {
  use<P extends Plugin>(plugin: P): App & ReturnType<P>;
}

export type Plugin = (app: App) => Record<string, unknown>;

When runtime data shapes are truly unpredictable, I often pair declaration files with runtime validation. Declaration files describe what the library claims to return, but if that library fetches JSON from a server, the actual payload may not match. In those cases I layer a validator like Zod on top of the typed client, a strategy outlined in Runtime Type Validation with Zod: Bridging TypeScript and External Data. The declaration file ensures your code calls the library correctly, while the validator ensures the library's output is what you expect at runtime. This two-layer approach has caught production issues for me where an API added a new nullable field without updating its JavaScript client.

A final practical note: always test your declarations with strict mode enabled and with strictNullChecks in particular. A declaration that looks correct with lax settings often hides missing null or undefined in return types. I run tsc --noEmit --strict specifically on the types folder in CI to ensure that a library update that introduces a new nullable path does not silently introduce unsoundness. If you are still migrating your codebase toward strictness, the incremental approach in Migrating to TypeScript Strict Mode: A Step-by-Step Approach works equally well for validating declaration files.

Frequently Asked Questions

Should I write declarations for every untyped dependency, or only the ones I use heavily?

Prioritize the libraries where you lose the most safety. In my experience, a utility library called in 80 places deserves a full declaration, while a one-off polyfill used in a single file can be typed with a minimal declare module 'polyfill' { const x: any; export default x; } placeholder. Start with the high-traffic dependencies, and expand coverage as you encounter friction. A partial type that covers the three methods you actually call is far more valuable than no type at all.

What is the difference between @types packages and local declaration files?

An @types package is a declaration file published to DefinitelyTyped and installed via npm. It is versioned separately from the library but follows semantic versioning to stay in sync. A local declaration file lives in your project's ./types folder and is maintained by you. Use @types when it exists and is accurate; use a local file when the library is niche, private, or when the upstream types are wrong and you need an immediate fix while waiting for a PR to merge.

How do I handle a library that modifies native prototypes, such as adding Array.prototype.customMethod?

Use interface merging on the global type. Create a declaration file that augments the global interface, for example interface Array<T> { customMethod(predicate: (x: T) => boolean): T[]; } inside a declare global block. Make sure that file is included in your compilation. Be cautious with this pattern — it affects every array in your project — and document clearly that the augmentation depends on importing the legacy library that performs the monkey-patch.

Can I generate declaration files automatically from JavaScript source or JSDoc?

Yes, if the JavaScript source already has JSDoc annotations, you can run tsc --allowJs --declaration --emitDeclarationOnly to generate .d.ts files. I've found this useful as a starting point, but the output often contains any for complex patterns and misses overloads. Treat generated files as a draft, then refine them manually for accuracy and readability. For pure JavaScript projects that want type checking without a build step, checkJs with JSDoc can be an alternative to maintaining separate declaration files.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards