What declare Does: Ambient Declarations
You'll learn how declare tells TypeScript about code that exists somewhere else, without creating any actual JavaScript output.
The Core Idea
Imagine you're writing documentation for a building that already exists. You're not constructing anything new—you're just describing what's already there so others can understand it. That's exactly what declare does in TypeScript.
The declare keyword creates ambient declarations: type-only descriptions of values, functions, or classes that exist at runtime but are defined elsewhere (perhaps in plain JavaScript, in the browser, or loaded via a script tag). When TypeScript compiles your code, declare statements vanish completely—they produce zero JavaScript output.
Why Ambient Declarations Exist
Sometimes you need to use code that TypeScript doesn't know about:
- Global browser APIs added by a third-party library
- Variables injected via a
<script>tag before your code runs - Legacy JavaScript modules without type definitions
- Compiler magic or build-time values
Without declare, TypeScript would complain that these identifiers don't exist. With declare, you say: "Trust me, this exists at runtime—here's its type."
The Difference from Normal Declarations
A normal variable declaration creates runtime code:
const API_KEY = "abc123"; // Emits: const API_KEY = "abc123";
An ambient declaration creates no code:
declare const API_KEY: string; // Emits: nothing
The declare version assumes API_KEY already exists when your code runs.
What You Can Declare
You can use declare with variables, functions, classes, namespaces, and modules—anything that might exist at runtime but isn't defined in your TypeScript source.
Key Takeaway: declare is TypeScript's way of documenting runtime values that exist elsewhere, providing type safety without emitting any JavaScript code.