The declare Keyword
What you'll learn: How to tell TypeScript about variables, functions, or types that exist at runtime without generating any JavaScript code.
What declare Does
The declare keyword is TypeScript's way of saying "trust me, this thing exists at runtime—I don't need to create it, just know about it for type checking."
Think of it like documenting something that's already in the room. You're not building a chair with declare—you're pointing at an existing chair and saying "that's a chair, and here's what it looks like."
Why You Need declare
When you write normal TypeScript code, the compiler generates JavaScript. But sometimes values already exist:
- Global variables from a
<script>tag - Browser APIs not covered by default types
- Variables injected by build tools
- Runtime values from external, non-TypeScript libraries
For these cases, you use declare to describe what exists without generating duplicate code.
Basic declare Syntax
// Tell TypeScript about a global variable that exists
declare const API_KEY: string;
// Now you can use it with type safety
console.log(API_KEY.toUpperCase()); // ✓ OK
// console.log(API_KEY.toFixed()); // ✗ Error: not a number
No JavaScript is generated for that declare const line. It's purely for TypeScript's type checker.
Common Use Cases
Describing global variables:
declare const VERSION: string;
declare let isProduction: boolean;
Describing global functions:
declare function gtag(command: string, id: string): void;
In declaration files (.d.ts):
// globals.d.ts
declare const window: {
myAppConfig: {
apiUrl: string;
};
};
Key Takeaway: Use declare to describe runtime values that TypeScript can't see, giving you type safety without generating any JavaScript output—it's documentation for the type checker, not executable code.