What is the meaning of the declare keyword in Typescript?
In TypeScript, declare
is used to tell the compiler about variables, functions, or types that exist in the global scope or in external libraries but are not defined in your code. It doesn’t generate any JavaScript output itself—rather, it’s for ambient declarations: letting TypeScript know “this thing is already declared elsewhere.”
1. Ambient Declarations
When you write something like:
declare let myGlobalVar: string;
you’re saying to TypeScript:
“There is a
myGlobalVar
of typestring
somewhere, trust me. I’m not defining it here, just declaring it for type-checking.”
The compiler doesn’t emit code for this line—it’s purely for type information. You might do this if myGlobalVar
is actually defined in some external script or environment.
2. Common Uses
-
Global Variables/Functions:
declare function myGlobalFunction(param: number): void;
This tells TypeScript that
myGlobalFunction
exists, so you can call it in your code without compile errors. -
Ambient Modules:
declare module "some-external-lib" { export function externalFn(): void; }
This is used in
.d.ts
files to provide type declarations for external libraries that don’t have their own typings. -
Declaration Merging:
declare global { interface Window { myCustomProperty: string; } }
So you can add properties to
Window
or other global objects.
3. No JavaScript Emitted
A key point is that declare
statements don’t produce JavaScript code. They’re purely a TypeScript construct for the compiler. When transpiled, TypeScript omits these lines because the real definitions are assumed to live elsewhere.
4. Why Use declare
?
- Type Safety: Let TypeScript know about externals (globals, third-party scripts) so it can type-check references to them.
- Ambient Modules: Provide type information for libraries lacking built-in or official
.d.ts
files. - Extending Global Objects: Safely add or merge declarations without re-implementing them.
If you’d like to strengthen your JavaScript foundations—on which TypeScript builds—consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers key concepts like prototypes, closures, and async patterns, helping you use TypeScript’s advanced features (like ambient declarations) with full confidence.