File tree Expand file tree Collapse file tree 2 files changed +23
-2
lines changed
Expand file tree Collapse file tree 2 files changed +23
-2
lines changed Original file line number Diff line number Diff line change @@ -82,6 +82,26 @@ export type Status = Enum<typeof Status>;
8282console .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
87107Enums 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
127147issues 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.
133154const StatusNaive = {
Original file line number Diff line number Diff line change 11{
22 "name" : " typescript-string-enums" ,
3- "version" : " 0.1.1 " ,
3+ "version" : " 0.2.0 " ,
44 "description" : " Typesafe string enums in TypeScript." ,
55 "main" : " dist/index.js" ,
66 "types" : " dist/index" ,
You can’t perform that action at this time.
0 commit comments