Ambient Declarations
declare const name: type;
declare function name(param: type): returnType;
declare module "module-name";
Using declare
The declare keyword describes an existing value, function, class, or other declaration that TypeScript should assume exists at runtime without TypeScript itself generating any code for it.
Example: Using declare
declare const VERSION: string;
// Assume VERSION is injected by the build tool at runtime.
console.log("Would use VERSION here in a real ambient setup");
Ambient Interfaces
Ambient interfaces can describe the shape of existing objects, such as ones provided by a browser API or a third-party script, without needing to provide any runtime implementation.
Example: Ambient Interfaces
declare interface Window {
myGlobalFlag: boolean;
}
// Describes a value assumed to exist on window at runtime.
console.log("Ambient interface declared for Window.myGlobalFlag");
Ambient Functions
Ambient function declarations describe functions implemented outside the current TypeScript file — often in plain JavaScript, a <script> tag, or a native environment — so TypeScript can still type-check calls to them.
Example: Ambient Functions
declare function trackEvent(name: string): void;
// trackEvent is assumed to be implemented elsewhere (e.g. a <script> tag).
console.log("Ambient function trackEvent declared");
Ambient Modules
An ambient module declaration describes the types exported by a JavaScript module that doesn't ship its own TypeScript types, effectively writing type information for a library from the outside.
Example: Ambient Modules
declare module "legacy-lib" {
export function doSomething(): string;
}
// Provides types for a JS module with no types of its own.
console.log("Ambient module declared for legacy-lib");
Declaration Files
Ambient declarations are commonly stored in .d.ts declaration files, which provide type information to the rest of a project without containing any executable code themselves.
Example: Declaration Files
// types.d.ts (declaration file, no runtime code)
// declare function legacyAdd(a: number, b: number): number;
console.log("Declaration files contain only type information, no executable code");
- Using
declare const x: stringand expecting it to create the variable, when it only tells the compiler it already exists and a missing value gives a runtimeReferenceError. - Putting an initializer in an ambient declaration, like
declare const VERSION = 1 + 1;, which is not allowed. - Writing function bodies inside
declare function, when ambient declarations must have only signatures.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: