← Back to TypeScript Course | Chapter 19: Enums Deep Dive | Lesson 4 of 6

Ambient Enums

Ambient enums describe enum declarations that exist outside the current TypeScript source, commonly in declaration files. They tell TypeScript about an existing runtime API rather than generating the enum itself.

Declaring an Ambient Enum

The declare enum syntax describes an enum's shape without providing any runtime implementation in the current TypeScript file — you're telling the compiler "this exists somewhere else, trust me."

Example: Declaring an Ambient Enum

typescript
declare enum NativeColor {
  Red,
  Green,
  Blue,
}
// Implementation assumed to exist elsewhere at runtime.
console.log("Ambient enum NativeColor declared");

Ambient Enums in Declaration Files

Ambient enums are commonly placed inside .d.ts declaration files to describe enum-like values that are actually supplied by another JavaScript library or the runtime environment itself.

Example: Ambient Enums in Declaration Files

typescript
// colors.d.ts
// declare enum NativeColor { Red, Green, Blue }
console.log("Ambient enums commonly live in .d.ts files");

Ambient Enum Members

Ambient enum declarations can include explicit initializers or leave members uninitialized, but either way their real meaning depends entirely on whatever external implementation actually backs them at runtime.

Example: Ambient Enum Members

typescript
declare enum HttpMethod {
  GET = "GET",
  POST = "POST",
}
console.log("Members can have explicit or implicit values, backed externally");

Ambient Enums and JavaScript APIs

Ambient declarations are the right tool when a JavaScript API genuinely exists at runtime but ships without its own TypeScript type definitions — you're filling in the type information TypeScript is missing.

Example: Ambient Enums and JavaScript APIs

typescript
declare enum ReadyState {
  Loading,
  Complete,
}
// Describes a JS API's real runtime enum-like values.
console.log("Ambient declarations fill in types for a real external API");

When to Use Ambient Enums

Reach for an ambient enum specifically when describing something implemented elsewhere — not as a way to create a brand-new enum for your own application, which should just be a normal enum declaration.

Example: When to Use Ambient Enums

typescript
// Use declare enum only for something implemented elsewhere.
// For your own app's enum, just write a normal enum:
enum AppStatus { Active, Inactive }
console.log(AppStatus.Active);
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.