-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path007-enum.ts
45 lines (32 loc) · 881 Bytes
/
007-enum.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// An enum type is actually an object. This enum
export enum Status {
"OK",
"Warning",
"Critical",
}
// is equivalent to
const StatusObj = {
OK: 0,
Warning: 1,
Critical: 2,
};
console.log(Status.OK); // 0
console.log(Status.Warning); // 1
console.log(Status[Status.OK]); // "OK"
// we have had many problems with enums in multiple projects and decided to
// use constant union types like instead:
type StatusType = "OK" | "Warning" | "Critical";
// or
const StatusValues = ["OK", "Warning", "Critical"] as const;
type StatusType2 = typeof StatusValues[number];
// This is clearer and does not imply a mapping.
// This is an example for when enums don't work so well
export enum Mapping {
MyA = "A",
MyB = "B",
}
function doSomething(param: Mapping): void {
}
// This does not work, even though "Mapping.MyA" equals "A"
// doSomething("A");
export {};