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

Adding Global Variables and Functions

Declaring global var, const, or function types for runtime globals injected by build tools or CDNs.

Adding Global Variables and Functions

What you'll learn: How to declare type signatures for global variables and functions that exist at runtime but TypeScript doesn't know about.

The Problem

Modern web development often involves runtime globals that get injected into your application by build tools, CDN scripts, or server-rendered HTML. Think of analytics libraries loaded via <script> tags, feature flags injected by your bundler, or configuration objects added to the window. TypeScript has no idea these exist, so it throws errors when you try to use them.

Declaring Global Variables

You use the declare global syntax combined with var, const, or function declarations to tell TypeScript about these runtime globals.

For a global variable injected by your build tool:

// globals.d.ts
declare global {
  var API_ENDPOINT: string;
  const BUILD_VERSION: string;
}

// Now usable anywhere without imports
console.log(API_ENDPOINT); // TypeScript knows this exists

Declaring Global Functions

Similarly, for functions added by CDN scripts or legacy code:

declare global {
  function trackEvent(eventName: string, properties: Record<string, unknown>): void;
  function initAnalytics(apiKey: string): void;
}

// Callable anywhere
trackEvent('page_view', { url: '/home' });

How It Works

These declarations create ambient types—they describe shapes that exist at runtime without generating any JavaScript output. The declare global block augments the global scope, making these identifiers available throughout your entire codebase without imports.

Key Takeaway: Use declare global with var, const, or function declarations to type runtime globals injected by external tools, ensuring TypeScript recognizes them without breaking your build pipeline.