declare and Ambient Types

The declare Keyword

declare tells TypeScript that something exists at runtime without providing it. Typical cases: global variables injected by a script tag or a bundler (__APP_VERSION__), or a value defined by another file.

// globals.d.ts
declare const __APP_VERSION__: string;          // replaced by Vite/webpack at build time
declare function gtag(cmd: "event", name: string, params?: Record<string, unknown>): void;
declare namespace Razorpay {
  interface Options { key: string; amount: number; currency: "INR"; order_id: string }
}

declare Promises Existence, Not Value

Example

The compiler trusts declare. If nothing actually defines the value at runtime, the program crashes with a ReferenceError.

declare const __APP_VERSION__: string;

console.log("type-checks fine");
console.log("version " + __APP_VERSION__.toUpperCase());

Output

type-checks fine
Uncaught ReferenceError: __APP_VERSION__ is not defined

declare global

Example

Inside a module, declare global { ... } adds to the global scope. Here we add a typed global variable and a new array method (global augmentation).

declare global {
  var APP_VERSION: string;
  interface Array<T> {
    sumBy(fn: (item: T) => number): number;
  }
}

globalThis.APP_VERSION = "2.4.1";
Array.prototype.sumBy = function <T>(this: T[], fn: (item: T) => number): number {
  return this.reduce((sum, item) => sum + fn(item), 0);
};

const cart = [{ price: 499, qty: 2 }, { price: 89, qty: 3 }];
console.log(APP_VERSION, cart.sumBy((i) => i.price * i.qty));

export {};

Output

2.4.1 1265

Note: Extending built-in prototypes is shown here only to demonstrate augmentation. In real projects prefer plain helper functions.