TypeScript declare Keyword
The declare keyword is used in TypeScript to create ambient declarations. It tells the compiler: "Assume this variable, function, class, or module exists at runtime, even if you can't see its implementation right now."
This is essential when using third-party JavaScript libraries that don't have type definitions, or when working with global variables injected by the environment (like the browser or a build tool).
1. Key Characteristic: No Output
Code marked with declare does not emit any JavaScript output. It is purely for the type checker during development.
declare const MY_GLOBAL_API_KEY: string;
console.log(MY_GLOBAL_API_KEY);
Compiled JS:
console.log(MY_GLOBAL_API_KEY);
(Notice the declare line is gone).
2. Declaring Globals
If a script loaded before yours defines a global variable, you need to tell TypeScript about it so it doesn't throw a ReferenceError during compilation.
Variables
declare var jQuery: (selector: string) => any;
jQuery('#app').hide();
Functions
declare function ga(command: string, ...args: any[]): void;
ga('send', 'pageview');
Classes
declare class Camera {
capture(): void;
}
let c = new Camera();
3. declare module
This is used to define types for modules that don't have their own type definitions. This is often done in .d.ts files.
declare module "my-untyped-library" {
export function doSomething(): void;
}
4. declare global
If you need to add properties to the global scope (like window or globalThis) from within a module (a file with imports/exports), you must wrap the declarations in declare global.
// analytics.ts
export {}; // Make this a module
declare global {
interface Window {
myAnalyticsData: any;
}
}
window.myAnalyticsData = { id: 123 };
5. declare in Classes
Inside a class, declare is used to tell TypeScript that a property exists, but it shouldn't emit code to initialize it. This is common when using decorators or libraries that handle initialization behind the scenes (like Babel).
class Animal {
// Tells TS: "This field exists, don't worry about initialization"
declare name: string;
}
programming/javascript/typescript/typescript programming/javascript/typescript/declaration-files