Skip to content

Declaration Files and Module Augmentation

Medium ~40 min

What you'll build

A .d.ts file for a hypothetical untyped library, plus a module augmentation that adds a custom method to String.

Goals

  • Write ambient declarations in .d.ts files
  • Declare module shapes for untyped imports
  • Augment existing interfaces (module augmentation)
  • Understand the triple-slash directive

Prerequisites

  • Interface and type aliases
  • ES module imports
  • Understanding of 'any' vs typed

Steps

  1. 1

    Declare an untyped module

    Create a .d.ts file that declares the shape of an untyped JS module. This lets you import it with full type safety.

    Code
    // types/legacy-lib.d.ts
    declare module 'legacy-lib' {
      export function format(date: Date, pattern: string): string;
      export function parse(str: string, pattern: string): Date;
      export const VERSION: string;
      export type Format = 'short' | 'long' | 'iso';
    }
    
    // usage.ts
    import { format, parse, VERSION } from 'legacy-lib';
    const s: string = format(new Date(), 'YYYY-MM-DD'); // fully typed

    Expected result

    Imports from 'legacy-lib' are fully typed despite no actual types in the JS.

  2. 2

    Declare a global variable

    Use declare global to add a global variable type, e.g. for a script tag that sets window.config.

  3. 3

    Augment String with a custom method

    Module augmentation adds to existing types. Add a reverse() method to String via declaration merging. Use with caution — it affects all strings.

  4. 4

    Augment a third-party module

    Add a custom property to an Express Request, for example. Module augmentation lets you extend types you don't own.

  5. 5

    Test the declarations

    Import the untyped module and use the augmented types. Verify the compiler catches type errors — if it doesn't, your declarations are too loose.

    Code
    // If format returns string, this should error:
    const n: number = format(new Date(), 'x'); // Error: string not assignable to number
    
    // Augmented method:
    const s: string = 'hello'.reverse(); // 'olleh' — typed as string

    Expected result

    Type errors appear when misusing the declared types, confirming they work.

Try it yourself

What you learned

You wrote declaration files — the bridge that lets TypeScript use the entire JavaScript ecosystem. Module augmentation extends types you don't own, safely.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic