Course contentsShow
← TypeScript
Lesson 1127 of 1,79626. Modules in TypeScriptFree lesson

Ambient Module Declarations

Using declare module syntax to define types for modules that don't have their own declarations.

Using Ambient Module Declarations

You'll learn how to create type definitions for third-party libraries or modules that don't ship with their own types.

What Are Ambient Module Declarations?

Imagine you're using a JavaScript library that has no TypeScript types. You're writing TypeScript code, but the compiler has no idea what types that library exports. Ambient module declarations solve this by letting you declare what types a module provides without actually implementing it.

The declare module syntax tells TypeScript: "Trust me, this module exists at runtime and here's its shape." You're essentially creating a type-level contract for code that lives elsewhere.

Why You Need This

When you import from a library without type definitions, TypeScript treats everything as any. Ambient module declarations let you add type safety without modifying the library's actual source code.

This is particularly useful for:

  • Legacy JavaScript libraries without native types
  • Internal company packages that haven't been typed yet
  • Quick prototyping before a full type definition exists

Basic Syntax

declare module "some-untyped-library" {
  export function doSomething(input: string): number;
  export const VERSION: string;
}

Now when you import from this module, TypeScript knows its shape:

import { doSomething, VERSION } from "some-untyped-library";

const result = doSomething("hello"); // TypeScript knows this returns number
console.log(VERSION.toUpperCase()); // TypeScript knows VERSION is string

Where to Put These Declarations

Typically, you create a .d.ts file (like types.d.ts or my-library.d.ts) in your project. The declarations in these files are automatically available throughout your project without explicit imports.

Wildcard Module Declarations

You can also declare modules using patterns:

declare module "*.json" {
  const value: any;
  export default value;
}

This tells TypeScript that any .json file import should be treated as having a default export of type any.

Key Takeaway: Use declare module to define types for external modules without their own declarations, bridging the gap between untyped JavaScript and your type-safe TypeScript code.