Ambient declaration

2 snippets in TypeScript

TSTypeScript

Declaration Files (.d.ts)

TS · Modules & Declaration Files
syntax
// filename.d.ts
declare function fn(param: Type): ReturnType;
declare const value: Type;
example
// global.d.ts
declare function trackEvent(name: string, data?: Record<string, unknown>): void;

declare const APP_VERSION: string;

declare interface ImportMeta {
  env: {
    VITE_API_URL: string;
    VITE_DEBUG: string;
  };
}
output
// .d.ts files provide type info without runtime code

Note Declaration files describe the shape of existing JavaScript code. They contain only type information — no executable code. TypeScript automatically picks up .d.ts files in your project. Most npm packages include their own or have a @types/package companion.

declare Keyword

TS · Modules & Declaration Files
syntax
declare const name: Type;
declare function fn(): Type;
declare class Name { ... }
declare module "name" { ... }
example
// Tell TypeScript about a global that exists at runtime
declare const gtag: (
  command: "config" | "event",
  targetId: string,
  params?: Record<string, unknown>
) => void;

// Tell TypeScript about a global class
declare class Stripe {
  constructor(apiKey: string);
  charges: {
    create(params: { amount: number; currency: string }): Promise<unknown>;
  };
}

gtag("event", "purchase", { value: 99.99 });
output
// declare tells TypeScript 'trust me, this exists at runtime'

Note declare is for things that already exist in the runtime environment but TypeScript cannot see (global scripts, CDN libraries, injected variables). It emits zero JavaScript. Using declare when the value does not actually exist leads to runtime crashes with no compile-time warning.