The global Scope in .d.ts Files
What you'll learn: How TypeScript decides whether a .d.ts file adds global types or requires imports, and how to control that behavior.
Script vs Module: The Critical Distinction
In TypeScript, a .d.ts file can behave in two fundamentally different ways:
Script mode (global): All declarations are automatically available everywhere without imports. Think of this like declarations written directly in the browser's global scope.
Module mode: Declarations must be explicitly imported to be used, just like regular TypeScript files.
The deciding factor? Whether the file contains top-level import or export statements.
The Rule
- No imports/exports → Script mode → Global scope
- Any import or export → Module mode → Scoped declarations
// global.d.ts - Script mode (global)
// No imports or exports = global scope
declare const APP_VERSION: string;
declare function initApp(): void;
// These are available everywhere automatically
// types.d.ts - Module mode
// Has export = module scope
export interface User {
id: number;
name: string;
}
// Must be imported: import { User } from './types'
Controlling the Behavior
To add global types from within a module file, use declare global:
// api-client.d.ts - Module file
export interface ApiConfig {
baseUrl: string;
}
// But we also want to add a global type:
declare global {
interface Window {
API_KEY: string;
}
}
To force a file to be treated as a module (even without exports), add an empty export:
// force-module.d.ts
declare const internalHelper: string;
export {}; // Makes this a module, not global
Key Takeaway: A .d.ts file without any import/export statements creates global ambient declarations available everywhere. Adding even a single export transforms it into a module requiring explicit imports. Use declare global to add global types from within modules.