Declaring Variables and Constants in Declaration Files
What you'll learn: How to use declare const and declare let to provide type information for global variables and constants that come from JavaScript libraries.
When you use a JavaScript library that creates global variables (like jQuery exposing $, or analytics scripts adding gtag), TypeScript doesn't know these exist. The library runs at runtime, but TypeScript's compiler has no idea what types these globals have—or that they exist at all.
This is where declare const and declare let come in. They tell TypeScript: "Trust me, at runtime there will be a global variable with this name and type." You're not creating the variable; you're describing something that already exists.
The declare Keyword with Variables
The declare keyword means "this exists somewhere else." When you write:
declare const API_KEY: string;
You're telling TypeScript: "There's a global constant called API_KEY of type string. I'm not defining it here, just documenting its type."
declare const vs declare let
Use declare const for values that shouldn't be reassigned:
declare const VERSION: string;
declare const MAX_RETRIES: number;
Use declare let for values that might change:
declare let currentUser: string | null;
declare let debugMode: boolean;
The difference mirrors regular const vs let: const signals immutability.
Real-World Example
Imagine a legacy analytics library loaded via <script> tag that creates a global analytics object:
declare const analytics: {
track: (event: string) => void;
identify: (userId: string) => void;
};
Now TypeScript knows this global exists and can type-check your calls to analytics.track("clicked").
Key Takeaway: Use declare const and declare let in declaration files to type global variables provided by external JavaScript, giving TypeScript awareness of runtime values without creating them yourself.