Skip to content

Commit bc329f8

Browse files
committed
Document Enum.keys() and Enum.values()
1 parent d8c7a07 commit bc329f8

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

README.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,26 @@ export type Status = Enum<typeof Status>;
8282
console.log(Status.RUNNING); // -> "running"
8383
```
8484

85+
Two helper functions are provided: `Enum.keys()` and `Enum.values()`, which resemble `Object.keys()`
86+
and `Object.values()` but provide strict typing in their return type:
87+
88+
``` javascript
89+
const FileType = Enum({
90+
PDF: "application/pdf",
91+
Text: "text/plain",
92+
JPEG: "image/jpeg",
93+
});
94+
type FileType = Enum<typeof FileType>;
95+
96+
const keys = Enum.keys(FileType);
97+
// Inferred type: ("PDF" | "Text" | "JPEG")[]
98+
// Return value: ["PDF", "Text", "JPEG"] (not necessarily in that order)
99+
100+
const values = Enum.values(FileType);
101+
// Inferred type: ("application/pdf" | "text/plain" | "image/jpeg")[]
102+
// Return value: ["application/pdf", "text/plain", "image/jpeg"] (not necessarily in that order)
103+
```
104+
85105
## Motivation
86106

87107
Enums are useful for cleanly specifying a type that can take one of a few specific values.
@@ -127,7 +147,8 @@ I might try to solve both problems by introducing constants for the string liter
127147
issues as well:
128148

129149
``` javascript
130-
type Status = "RUNNING" | "STOPPED";
150+
// Typo on "STOPPED" not caught by anything below without additional boilerplate.
151+
type Status = "RUNNING" | "STPOPED";
131152

132153
// Naive attempts to define constants for these don't work.
133154
const StatusNaive = {

0 commit comments

Comments
 (0)