Declaring Global Variables
What you'll learn: How to properly type global variables like window properties using TypeScript's ambient declaration syntax.
The Problem with Globals
Sometimes you need to work with global variables that exist at runtime but TypeScript doesn't know about. Maybe you've added a property to window in a browser script, or a third-party library creates a global variable. Without proper declarations, TypeScript will complain that these don't exist.
Using declare var, declare let, and declare const
TypeScript provides three keywords for declaring global variables without initializing them:
// Tells TypeScript "trust me, this variable exists globally"
declare var myGlobal: string;
declare let userConfig: { theme: string };
declare const API_KEY: string;
These declarations don't generate any JavaScript code — they're purely for the type system. They tell TypeScript "this variable will exist at runtime, and here's its type."
Real-World Example: Extending window
A common use case is typing custom properties on window:
declare var version: string;
// Now TypeScript knows about it
console.log(version); // No error
Choosing the Right Keyword
declare var: The variable can be reassigneddeclare let: Block-scoped and reassignable (rarely used for globals)declare const: Read-only, cannot be reassigned
Use declare const when the global shouldn't change. Use declare var for traditional mutable globals.
Key Takeaway: Use declare var, declare let, and declare const to provide type information for global variables that exist at runtime but aren't visible to TypeScript's type checker — no runtime code is generated, only compile-time safety is added.