Course contentsShow
← TypeScript
Lesson 1173 of 1,79627. Declaration FilesFree lesson

declare global Syntax

Using the declare global block to add new types, interfaces, or values to the global namespace.

Using declare global Syntax in TypeScript

What you'll learn: How to use the declare global block to safely extend the global namespace with new types, interfaces, or values.

What Is declare global?

When you're working in a module file (one with import or export statements), TypeScript treats your code as isolated from the global scope. But sometimes you need to add types to truly global objects like Window, globalThis, or even your own global variables. The declare global block creates a bridge from your module context into the global namespace.

Think of it like a diplomatic channel between two countries: your module is one territory, and the global namespace is another. The declare global syntax lets you officially register new citizens (types, properties, functions) in the global territory, even though you're standing in module territory.

The Basic Syntax

// In a module file (has import/export)
export {}; // Forces module context

declare global {
  // Augment existing global types
  interface Window {
    myCustomProperty: string;
  }
  
  // Add new global variables
  var MY_GLOBAL_CONFIG: { apiUrl: string };
  
  // Add new global types
  type UserId = string;
}

// Now you can use these globally
window.myCustomProperty = "Hello";
const config = MY_GLOBAL_CONFIG;
const id: UserId = "user-123";

Why You Need It

Without declare global, you'd get errors trying to reference custom global properties. The block tells TypeScript "these things exist at runtime in the global scope, trust me."

Key Takeaway: Use declare global inside module files to augment the global namespace with types, interfaces, or variable declarations that should be accessible everywhere without imports.