This series will be updated as a patch for TypeScript Introduction Field Notes.
The purpose of the Ambient Enums external enumeration
As we mentioned in Lecture 9, enumerations are a particularly bad feature in TypeScript because enumerated types are basically only compatible with their own types.
But I’m guessing that Ambient Enums, which define enumerations that have been defined elsewhere, can work around (” circumventing “) the problem of enumerations being self-compatible.
But the TypeScript documentation doesn’t have a good example of what or how these things work, except for the fact that external enumerations that don’t have an initial value are always computed, and that they are erased when translated into JavaScript. However, in combination with the fact that it is erased during translation, it is likely to be used only in type definition files. D. ts (because if an external enumeration defined in the. Ts module is erased, the enumeration value will not be found at runtime).
Here’s an example:
First define types.d.ts:
declare enum A {
A = "A",
B = "B"
}
export type CmpA = (ele: A) = > boolean;
export {};
Copy the code
Then define business.ts:
import { CmpA } from "./types";
enum A {
A = "A",
B = "B"
}
// C1: enumerated types are compatible
const c: CmpA = (ele: A) = > {
switch (ele) {
case A.A:
return true;
default:
return false; }};export {};
Copy the code
As indicated in the business.ts C1 comment, an anonymous arrow function that uses enumeration A can be assigned to A variable c of type CmpA, which means that the external enumeration and enumeration A are compatible. So that’s what I understand about external enumerations.
codesandbox playground