← Back to TypeScript Course | Chapter 9: Modules and Namespaces | Lesson 6 of 7

Ambient Declarations

Ambient declarations tell TypeScript about code that exists elsewhere, such as a JavaScript library or global variable. They describe types without generating JavaScript implementation code.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
// 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");
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.