Global Type Aliases and Namespaces
What you'll learn: How to create type aliases and namespaces that are accessible from anywhere in your project without explicit imports.
What Are Global Type Aliases and Namespaces?
When you use declare global, you can define type aliases and namespaces that become available in every TypeScript file in your project automatically — no imports required. This is powerful for types that represent truly application-wide concepts, like user identities, configuration shapes, or domain models used everywhere.
Think of it like declaring universal constants in your codebase: instead of each file importing a "User" type, you make it globally known so every file just "knows" what a User is.
Creating Global Type Aliases
Inside a declare global block, you can define type aliases that every file can reference:
// globals.d.ts
export {}; // Force this file to be a module
declare global {
type UserID = string;
type Timestamp = number;
type ApiResponse<T> = {
data: T;
status: number;
};
}
Now in any file in your project:
// user.ts - no imports needed!
function getUserById(id: UserID): void {
console.log(`Fetching user ${id}`);
}
const timestamp: Timestamp = Date.now();
const response: ApiResponse<string> = {
data: "hello",
status: 200
};
Creating Global Namespaces
You can also declare namespaces globally to group related types:
// globals.d.ts
export {};
declare global {
namespace App {
type Config = {
apiUrl: string;
timeout: number;
};
type Environment = "development" | "production";
}
}
Access them anywhere with the namespace prefix:
// config.ts
const config: App.Config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
const env: App.Environment = "production";
When to Use Global Declarations
Global types work best for:
- Core domain models used across your entire application
- Configuration shapes
- Universal ID types or branded primitives
- Framework extensions (like augmenting Window or Express)
Avoid globals for types specific to one module or feature — explicit imports keep dependencies clear.
Key Takeaway: Global type aliases and namespaces defined with declare global are accessible from any file without imports, perfect for truly universal concepts but should be used sparingly to avoid namespace pollution.