What is an 'ambient enum' declared with 'declare enum', and when would you use one?
Short answer
declare enum describes an enum that ALREADY EXISTS at runtime (typically defined in plain JavaScript or another compiled module) without generating any new runtime code itself — used in .d.ts files to describe a third-party library's runtime enum-like object so TypeScript can…
Advertisement
AModel answer
declare enum describes an enum that ALREADY EXISTS at runtime (typically defined in plain JavaScript or another compiled module) without generating any new runtime code itself — used in .d.ts files to describe a third-party library's runtime enum-like object so TypeScript can type-check code that references it.
// library.d.ts
declare enum Color {
Red,
Green,
Blue
}
// no JS object is generated here -- it must already exist at runtime, provided by the libraryReal-world example
Writing a declaration file for a JavaScript library that exports an enum-like object, so TypeScript users of that library get type checking.
Likely follow-ups
- How does this interact with the 'const enum' inlining behavior when the library itself defines a const enum?
Related topics