Ambient declarations tell TypeScript about code or variables that exist somewhere else, like in another file or a library. This helps TypeScript understand your code without having the actual code present.
Ambient declarations in Typescript
declare var variableName: type; declare function functionName(params): returnType; declare class ClassName { ... } declare module 'module-name' { ... }
Use declare to tell TypeScript about something without creating it in the output JavaScript.
Ambient declarations do not generate code; they only provide type information.
myGlobalVar of type string.declare var myGlobalVar: string;greet that takes a string and returns nothing.declare function greet(name: string): void;
Person with a property and methods, without defining it.declare class Person { name: string; constructor(name: string); greet(): void; }
my-library and what it exports.declare module 'my-library' { export function doSomething(): void; }
This program declares an ambient global variable externalValue. We assign it a value outside TypeScript's knowledge and then print it. TypeScript won't complain about externalValue because of the declaration.
declare var externalValue: number; globalThis.externalValue = 42; console.log("The external value is", externalValue);
Ambient declarations are only for telling TypeScript about existing code; they do not create variables or functions themselves.
Use ambient declarations carefully to avoid mismatches between declared types and actual runtime behavior.
Ambient declarations often appear in .d.ts files, which only contain type information.
Ambient declarations use declare to describe code that exists elsewhere.
They help TypeScript understand external or global code without generating JavaScript.
Commonly used for global variables, functions, classes, and modules from other sources.