@@ -84,22 +84,7 @@ console.log(state);
84
84
85
85
### Why not string literals?
86
86
87
- Using string literals throughout a program leaves it vulnerable to bugs caused by typos or
88
- incomplete refactors. For example:
89
-
90
- ``` javascript
91
- type Status = " RUNNING" | " STOPPED" ;
92
-
93
- ...
94
-
95
- // Typo "SOTPPED" is not caught by typechecker.
96
- // Pretty bad bug- this block will never run.
97
- if (state .status === " SOTPPED" ) {
98
- soundTheAlarm ();
99
- }
100
- ```
101
-
102
- Further, string literals make refactoring difficult. Suppose I have two enums:
87
+ String literals make refactoring difficult. Suppose I have two enums:
103
88
104
89
``` javascript
105
90
type Status = " RUNNING" | " STOPPED" ;
@@ -111,6 +96,10 @@ way to do it. I can't globally find/replace `"RUNNING"` to `"STARTED"` because i
111
96
the unrelated string constants representing ` TriathlonStage ` . Instead, I have to examine every
112
97
occurrance of the string ` "RUNNING" ` to see if it needs to change.
113
98
99
+ Another disadvantage of string literals comes when using IDE autocomplete features. It's convenient
100
+ to be able to type ` Status. ` and have autocomplete suggest ` Status.RUNNING ` and ` Status.STOPPED ` ,
101
+ but with string literals no such suggestion appears with current IDEs.
102
+
114
103
I might try to solve both problems by introducing constants for the string literals, but this has
115
104
issues as well:
116
105
@@ -175,7 +164,7 @@ function Enum<V extends string>(...values: V[]): { [K in V]: K }
175
164
176
165
the type parameter ` V ` is thus inferred to be ` "RUNNING" | "STOPPED" ` . Then the return type
177
166
` { [K in V]: K } ` is a mapped type which describes an object whose keys are the types that
178
- make up ` V ` and for each such key has a value equal to that key. Hence, the type of
167
+ make up ` V ` and for each such key has a value of the same type as that key. Hence, the type of
179
168
` Enum("RUNNING", "STOPPED") ` is
180
169
181
170
``` javascript
0 commit comments