Ambient Enums
In this page:
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
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
// 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
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
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
// 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: